javascript - background to content script messaging: message sent before content script is ready -
when trying pass message background script content script, i'm using
chrome.tabs.query( {active: true, currentwindow: true}, function(tabs) { chrome.tabs.sendmessage( tabs[0].id, {greeting: "hello"}, function(response) { console.log(response.farewell); } ); });
in background script , corresponding listener
chrome.runtime.onmessage.addlistener( function(request, sender, sendresponse) { if (request.greeting === "hello") { sendresponse({farewell: "goodbye"}); } });
in content script (according the documentation).
now, might want send content script when web request of current tab has finished, e.g.,
chrome.webrequest.oncompleted.addlistener( // sender code above )
i found, background script sends message when content script hasn't been injected page yet. consequently, there not reply.
how fix this? there event listen in background script tells me when content script has been loaded?
the safest way send message from content script indicating ready, , reply background page.
you can, instance, add queue per tab id , push messages there, , when message tab arrives feed queue it.
you try using programmatic injection instead of manifest injection:
chrome.tabs.executescript({file: "yourcontentscript.js"}, function() { // after above finishes executing /* messaging code */ });
however, if call before navigation committed, i.e. before context of tab changed (which can happen webrequest
events), script try inject in previous page , wiped transition.
Comments
Post a Comment