I am able to pass data from my webpage to chrome extension. My code goes as follows.
var id = "myExtensionId";
chrome.runtime.sendMessage(id, { messageFromWeb: "Sample message" }, function (response) {
});
I am able to get the tab Id at the extension side. But how can I send back data from the extension to the tab? Is the 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" });
does not throw error.
How should be listening at the web page to get events from extension?
Since Chrome extensions are event-driven because of their architecture, once the injected scripts have access to the page's variables and functions, they can pass it to the content script. The content script then passes the these objects to the background page.
When sending a message to the content script, we need to specify which tab to send it to. Therefore, we need to retrieve the active tab information first, and then use tabs. sendMessage . To use the tabs API and to have access to the active tab, you need to add tabs and activeTab under permissions in your manifest.
tabs. sendMessage( tab.id, youtPayload, function (response) { // do something here if you want } ); }); }); That's it!
Because the content script and the scripts in the website can see the same DOM, you can use it to communicate between them. Is as easy as:
// data you want to sent
var data = {
random: 'Some data',
more: 'More data'
};
// send data through a DOM event
document.dispatchEvent(new CustomEvent('csEvent', {detail: data}));
// Listen you CRX event
document.addEventListener('csEvent', function (event) {
var data = event.detail;
// Do something with you data from CRX
});
How to do it depends on which type of connection you need: one-time or long-lived. From Chrome Developer page Messaging:
There is a simple API for one-time requests and a more complex API that allows you to have long-lived connections for exchanging multiple messages with a shared context.
If you only want to send a response back, here is an example:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
sendResponse({farewell: "Message back!"});
});
Edited to add content script to website script way
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With