3

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.

2
  • Works fine for me. Why do you think that it doesn't work? Can you show your manifest file?
    – Rob W
    Jun 2, 2014 at 10:50
  • I updated my question with your request. Thanks. Jun 2, 2014 at 11:03

1 Answer 1

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.