javascript - Pass data from chrome extension to webpage -
i able pass data webpage chrome extension. code goes follows.
var id = "myextensionid"; chrome.runtime.sendmessage(id, { messagefromweb: "sample message" }, function (response) { });
i able tab id @ extension side. how can send data extension tab? following code correct?
chrome.runtime.onmessageexternal.addlistener( function(request, sender, sendresponse) { if (request.messagefromweb) { console.log(request.messagefromweb); } chrome.tabs.sendmessage(sender.tab.id,{ greeting: "hello" }); } );
the code, chrome.tabs.sendmessage(sender.tab.id,{ greeting: "hello" });
not throw error. how should listening @ web page events extension?
from content script website script
because content script , scripts in website can see same dom, can use communicate between them. easy as:
content script:
// data want sent var data = { random: 'some data', more: 'more data' }; // send data through dom event document.dispatchevent(new customevent('csevent', {detail: data}));
website script:
// listen crx event document.addeventlistener('csevent', function (event) { var data = event.detail; // data crx });
from content script background script
how depends on type of connection need: one-time or long-lived. chrome developer page messaging:
there simple api one-time requests , more complex api allows have long-lived connections exchanging multiple messages shared context.
if want send response back, here example:
chrome.runtime.onmessage.addlistener( function(request, sender, sendresponse) { console.log(sender.tab ? "from content script:" + sender.tab.url : "from extension"); sendresponse({farewell: "message back!"}); });
edited add content script website script way
Comments
Post a Comment