0

I'm working on a chrome extension where I need popup.js to send a message to content.js, and then log the response. I'm running this example exactly as copied from the chrome developer guide on messaging: https://developer.chrome.com/extensions/messaging

popup.js:

function handleClick() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
    console.log(response.farewell);
  });
});
}
document.getElementById('bttn').addEventListener('click', handleClick);

content.js:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log(sender.tab ?
            "from a content script:" + sender.tab.url :
            "from the extension");
if (request.greeting == "hello")
  sendResponse({farewell: "goodbye"});
});

the message from popup.js is received by content.js because the console logs "from the extension", but response is not received by popup.js because there is no console log for "goodbye".

md1630
  • 841
  • 1
  • 10
  • 28
  • 2
    The popup is a separate window so it has its own devtools console. Right-click the popup, then click "inspect". – wOxxOm Mar 24 '20 at 08:04
  • thank you. I just did this, but don't see it in that console either. I also tried to alert() the response, and not getting the alert either – md1630 Mar 24 '20 at 08:08
  • in chrome://extensions, now I see an error: Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist. – md1630 Mar 24 '20 at 08:11
  • as well as another error: Error handling response: TypeError: Cannot read property 'farewell' of undefined – md1630 Mar 24 '20 at 08:14
  • It means the content script wasn't running at the time the message was sent. Make sure your `"matches"` is correct and reload the tab after you reload/re-enable the extension itself. P.S. when popup's devtools is shown and is the active window you can press F5 key to reload it to see any errors that occur during its startup. – wOxxOm Mar 24 '20 at 08:22
  • very sorry, I did all of this but it's still not working for me. :( – md1630 Mar 24 '20 at 08:32
  • Well, without [MCVE](/help/mcve) I can only keep guessing and that isn't productive. MCVE would include the URL of the tab, manifest.json, popup.html, any other relevant details you can cite. Meanwhile you can verify the content script is present by looking in web tab's devtools -> Sources -> Content scripts subpanel on the left (or in the console's toolbar selector for the context - it shows `top` by default). – wOxxOm Mar 24 '20 at 08:39

0 Answers0