10

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?

1 Answer 1

12

From content script to website script

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:

Content script:

// 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})); 

Website script:

// Listen you CRX event document.addEventListener('csEvent', function (event) { var data = event.detail; // Do something with you data from CRX }); 

From content script to background script

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

Sign up to request clarification or add additional context in comments.

9 Comments

I get the following error: Uncaught TypeError: Cannot read property 'addListener' of undefined
Where did you execute this code? Is in the background js?
I am executing the script in the web page. I am able to send data from web page to the extension. The following is my code to receive message from extension. var port = chrome.runtime.connect("myExtensionId"); port.onMessage.addListener( function (request, sender, sendResponse) { alert('Got from EXTN'); });
Ok, I didn't understand you. So you already have a content script in the page and want to send data from your content script to the website, right? Is the website owned by you (so you can edit the website)?
Yes I want the extension to communicate with my website
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.