sending data between from content.js to popup.js in a chrome extension

41 Views Asked by At

I would appreciate a minimal example showing how to send data (a string) from content.js to popup.js/html, in a chrome extension (I am using v3 manifest).

Starting with the documentation: it only talks about messaging between service worker (I am assume background.js) and content.js, not popup.js. What I have tried:

1- The broadcast API, which did not do anything, no errors but at the same time nothing is being printed to the console or alerted, as if it was never called.

2- I tried listening to the messages directly from popup.js, I get an exception saying: "Error: Could not establish connection. Receiving end does not exist" for Chrome Extension, my take away was, you can not listen to sendMessage from popup.js but you have to do it from background.js

3- I tried using getBackgroundPage() as a few examples on the net suggested, but I ran into: getBackgroundPage() is undefined I found a few sources saying it is obsolete in V2 manifest, but I don't recall where did I read that.

my code setup right now.

//background.js 
chrome.runtime.onMessage.addListener
(
    function(request, sender, sendResponse) {
    console.log(sender.tab ?
            "from a content script:" + sender.tab.url :
            "from the extension");
    console.log("received data", request);
});


//content.js
(async () => {
    const response = await chrome.runtime.sendMessage({Data:"Data"});
    })();

//popup.js
//not sure what to put here? I tried chrome.runtime.onMessage() but it never get triggered

In this setup background.js receives the data successfully, but I want to display it in popup.html/js eventually, if there is a way to send directly from content to popup I would like that, if not and I have to go through background.js then I don't mind, but I would appreciate a code working sample to understand how it all connect together.

Finally I would like to emphasize that I want to send from content.js to popup.js and not vice versa, I found multiple examples online that touches on sending from popup.js to content.js which is the opposite of I want to do.

0

There are 0 best solutions below