Search code examples
javascriptgoogle-chromegoogle-chrome-extension

Chrome Extension message not sending response (undefined)


For future reference: I solved this by switching the onMessage/sendMessage to the background script and the content script, respectively. I'm not sure why this worked, but it did.

I've been trying to debug this for the past three hours--I'm building a chrome extension and I've been getting "undefined" as the response to a message I send. I'm trying to get the text of the tab the user is on and use it to do some analysis.

Content Script:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if (request.method == "collectText") {
            sendResponse({data: document.body.innerText, method: "collectText"});
        }
        return true;
    }
);

Popup Script:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {method: "collectText"}, function(response) {
      if (response) {
        txt = response.data;
        console.log("response arrived");
        console.log(txt);
      } else {
        console.log("No response.");
      }
  });
});

The console.logs are currently there so that I know if the data is coming back (it's not--"No response" is logged every time the scripts run, and txt ends up undefined). I'm not sure why this isn't working (& I've tried many variations on the same scripts to no avail). I'm not getting any errors in the console of either the extension or the page I'm on. Should I be using a background script instead of writing everything inside popup.js?

Thank you!


Solution

  • For future reference: I solved this by switching the onMessage/sendMessage to the background script and the content script, respectively. I'm not sure why this worked, but it did.