Reputation: 531
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?
Upvotes: 10
Views: 7267
Reputation: 2358
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
Upvotes: 12