Passing data from chrome extension to webpage

I can transfer data from my webpage to chrome extension. My code looks like this.

var id = "myExtensionId";
    chrome.runtime.sendMessage(id, { messageFromWeb: "Sample message" }, function (response) {
});

      

I can get the ID of the tab on the extension side. But how can I send 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 an error.   How should I listen to a web page to receive events from an extension?

+3


source to share


1 answer


From script content to website script

Since the content of the script and scripts on the website can see the same DOM, you can use it to communicate between them. It's simple:

Script content:

// 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 script content to script background

How to do this depends on what type of connection you want: disposable or long lived. From the Chrome Messaging developer page :

There is a simple API for one-time requests and a more complex API that allows you to have long-lived connections to exchange multiple messages with a common context.

If you only want to post a response, here's 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 script content to website script way

+3


source







All Articles