问题
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.
回答1:
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
send messages to extension's own pages; content scripts are not considered such.
To send a message to a content script, you have to use the chrome.tabs.sendMessage API call by tab's tabId
.
Assuming you want the current visible tab:
function click(e) {
if ( e.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.
来源:https://stackoverflow.com/questions/23992698/popup-script-and-content-script-cant-communicate