javascript - Popup script and content script can't communicate? -
my problem can't seem message chrome.extension.sendmessage("on"); popup.js transfer content.js.
code 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 message when add listener code. content.js can't seem it.
code 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 appreciated.
chrome.extension.sendmessage non-canonical name.
the old, deprecated api chrome.extension.sendrequest, , new api chrome.runtime.sendmessage, , event likewise chrome.runtime.onmessage.
that said, problem trying send message content script. chrome.runtime.sendmessage send messages extension's own pages; content scripts not considered such.
to send message content script, have use chrome.tabs.sendmessage api call tab's tabid.
assuming want 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 want all tabs, pass {} query , iterate on tabs.
finally, take note of content scripts inject time quirks.
Comments
Post a Comment