javascript - Chrome.runtime.onMessage doesn't work -
i building chrome.extension.
in it, have button
in popup.html
(that appears in top-right toolbar). popup.html
file linked htmljs.js
file has following code:
(function(){ window.onload = init; function init(){ if (!chrome.runtime) { // chrome 20-21 chrome.runtime = chrome.extension; } else if(!chrome.runtime.onmessage) { // chrome 22-25 chrome.runtime.onmessage = chrome.extension.onmessage; chrome.runtime.sendmessage = chrome.extension.sendmessage; chrome.runtime.onconnect = chrome.extension.onconnect; chrome.runtime.connect = chrome.extension.connect; } button.onclick = function(){ console.log("working onclick!"); // working! // send message content script chrome.runtime.sendmessage(["testing"]); } } })();
and popup.js
(that operates on web pages stackoverflow, called content-script
), has following code:
(function () { window.onload = init; function init() { if (!chrome.runtime) { // chrome 20-21 chrome.runtime = chrome.extension; } else if (!chrome.runtime.onmessage) { // chrome 22-25 chrome.runtime.onmessage = chrome.extension.onmessage; chrome.runtime.sendmessage = chrome.extension.sendmessage; chrome.runtime.onconnect = chrome.extension.onconnect; chrome.runtime.connect = chrome.extension.connect; } // when receiving message html popup.html chrome.runtime.onmessage.addlistener(function (message, messagesender, sendreponse) { // sender messagesender: https://developer.chrome.com/extensions/runtime#type-messagesender // function sendresponse: needed send response, not needed in current context (?) console.log(message); // not work console.log("w"); // not work alert("w"); // not work sendreponse(); // not work return true; }); } })();
i have both consoles open (the stackoverflow webpage's , popup.html
's), , console.log("working onclick!");
works. appears message not @ received content-script.
here's manifest.json if matters.
update:
using accepted answer, needed:
// active tab, , send id along message using tabs.sendmessage chrome.tabs.query({active:true}, function(tabs){ // send message content script chrome.tabs.sendmessage(tabs[0].id, ["testing"]); });
to send message content script, need use chrome.tabs.sendmessage
.
Comments
Post a Comment