user3698990
user3698990

Reputation: 47

Popup script and content script can't communicate?

My problem is that I can't seem to get the message chrome.extension.sendMessage("on"); from my popup.js transfer to my content.js.

Code from the popup.js:

function click(e) {
    if ( e.target.id == "green"){
        chrome.extension.sendMessage("start");
        console.info("oN");
        return;
    }

    if ( e.target.id == "red"){
        chrome.extension.sendMessage("stop");
        console.info("oFF");
        return;
    }
}

The popup.js receives the message perfectly well when i add a listener to the code. But my content.js can't seem to get it.

Code from the content.js:

chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.info("ok");
    }
);

Manifest:

"content_scripts": [
{
    "matches": ["<all_urls>"],
    "js": ["content.js"],
    "run_at": "document_end"
}
],

Any help is greatly appreciated.

Upvotes: 3

Views: 1132

Answers (1)

Xan
Xan

Reputation: 77591

chrome.extension.sendMessage is a non-canonical name.

The old, deprecated API is chrome.extension.sendRequest, and the new API is chrome.runtime.sendMessage, and the event is likewise chrome.runtime.onMessage.


That said, your problem is trying to send a message to a content script. chrome.runtime.sendMessage sends messages to extension's own pages; content scripts are not considered such. See the chrome.runtime.sendMessage docs

Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage.

To send a message to a content script, you have to use the chrome.tabs.sendMessage API call using the tab's tabId.

Assuming you want the current visible tab:

function click(event) {
  if (event.target.id == "green") {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      chrome.tabs.sendMessage(tabs[0].id, "start");
    });
    console.info("oN");
    return;
  }
  /* ... */
}

If you want all tabs, just pass {} to query and iterate over tabs.

Finally, take note of content scripts inject time quirks.

Upvotes: 3

Related Questions