0

I'm trying to message passing in a chrome extension. I follow this example (see here)- :

content_script:

chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});

background:

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

popup.js

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")
        console.log("message recive")
        sendResponse({farewell: "goodbye"});
});

Although I did copy-paste - the message is not sent. Error pops up:

Error in event handler for (unknown): TypeError: Cannot read property 'farewell' of undefined

Where is the mistake?

agro
  • 57
  • 12

1 Answers1

1

The popup does not exist while it's closed.

As such, at the moment when message is sent there is likely no-one listening, so the callback called with undefined as response (and with chrome.runtime.lastError set).

From an architecture standpoint, the background page is the one always available to process a message; as such, onMessage listeners are, in most (not all) cases better off in there.

I would recommend taking a look at this question as well, where I explain some concepts in more detail: Pass a variable from content script to popup.

Also, just in case, all this greeting-goodbye sample code is just an example; you can pass anything JSON-serializable.

Xan
  • 74,770
  • 16
  • 179
  • 206