0

I did what's in the documentation but I got an error saying Cannot read property 'farewell' of undefined in the background page.

my background.js

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
   console.log(response.farewell);
    console.log('ytr');
  });
});

The msg is sent because my console.log('test') did print out.

my contentScript.js look like this

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  });

and I did declare permission tabs and activeTab in manifest.json. What else I missed?

  • To get farewell's value you can use `chrome.extension.onRequest.addListener()` in background page and make sure that your background page is registered in manifest.json [https://developer.chrome.com/extensions/extension](https://developer.chrome.com/extensions/extension) – Touhid Nov 13 '14 at 07:46
  • @Touhid why use onRequest not tabs.query? – newbie programmer Nov 13 '14 at 08:12
  • to get value by sending this funciton `sendResponse({farewell: "goodbye"});` – Touhid Nov 13 '14 at 08:36
  • @Touhid Incorrect. To receive `sendResponse`-sent reply, you need to use the callback of `sendMessage`, not the `onMessage` listener. – Xan Nov 13 '14 at 11:31
  • oh. So my conjecture is wrong. – Touhid Nov 13 '14 at 11:58

1 Answers1

1

If response is undefined (and that's what "Cannot read property ... of undefined" means), then there was an error sending the message.

In this case Chrome calls the callback with response == undefined and sets chrome.runtime.lastError.

You need to check the error value:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
    if(chrome.runtime.lastError) {
      console.error(chrome.runtime.lastError.message);
      return;
    }
    console.log(response.farewell);
    console.log('ytr');
  });
});

My bet is - your content script somehow did not get injected properly. See this answer for some pointers.

Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206