0

I am developing a Chrome extension. I want to pass a message from the contentScript.js to my popup.js file. This should happen when the contentScript.js loads. From what I have read, I use " chrome.runtime.sendMessage" to do this. I am not sure how to actually receive it in the popup.js file. I have read that you need to use "chrome.runtime.onMessage.addListener", however it does not work.

contentScript.js

window.onload = function() {  
    var markup = document.documentElement.innerHTML;
    alert(markup);

    chrome.runtime.sendMessage({a:"b"});

    //This alert fires.
    alert("Content sent");
};

popup.js

    chrome.runtime.onMessage.addListener(
       function(request, sender, sendResponse) {
        //This alert never fires. 
        alert("Message Received!"); 
       }
   );

There are no errors received in the console, nor the extensions page. The message is either never sent, or is sent on not received. What am I missing?

Dave
  • 2,473
  • 2
  • 30
  • 55
  • 1) The popup runs only when shown so the usual approach is to send a message from the popup via tabs.sendMessage with a tab id. 2) Note that the popup is a separate window so it has its own separate devtools: right-click inside the popup and select "inspect" in the menu. – wOxxOm Nov 09 '21 at 17:44
  • Does https://stackoverflow.com/questions/20019958/chrome-extension-how-to-send-data-from-content-script-to-popup-html help at all? – Andy Nov 09 '21 at 17:47
  • @wOxxOm, I want this to run on the page as soon as it loads without any interaction from the user. User navigates to page --> content processes DOM --> sends message to the popup. Is this not feasible? – Dave Nov 09 '21 at 17:51
  • @Andy I did look at that, however it looks like the user needs to click the extension and then click a button to get the desired action. – Dave Nov 09 '21 at 17:56
  • Since the popup may be closed, this won't work. Either do the work in the content script or use a background script or something else, depending on what specifically you're doing. – wOxxOm Nov 09 '21 at 18:25
  • @wOxxOm, Thanks. Looks like it is back to the drawing board. – Dave Nov 09 '21 at 19:22

0 Answers0