1

noobie JS dev here, I am developing a chrome extension and I have 2 scripts, background.js and popup.js - I need to call a function in popup.js based on some action in background.js, so I found I can send a message. This works fine for me, but I also need to send reponse back to the background.js script and I get this error at popup.html:1

Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

Funny thing is, console from inspect view: background @chrome://extensions/ logs the response fine, but console from inspecting the popup logs undefined and shows the error.

Thank you for any help.

(the code below is simplified)

background.js:

    chrome.runtime.sendMessage('hi', response => {
      console.log(response);
    });

popup.js

chrome.runtime.onMessage.addListener(
    function (message, sender, sendResponse) {
        if (message == 'hi') {
            //some DOM actions here
            sendResponse('bye');
        }
        return true;
    });
Dejw
  • 23
  • 3
  • Assuming you know the popup code runs only when it's shown so your background script should send the message at an appropriate time, the only obvious thing (without seeing the actual extension) is there's no need for `return true` when responding synchronously. – wOxxOm May 07 '19 at 19:25
  • @wOxxOm Yeah, I know it runs only if popup is open, that part is fine. I deleted the return true; and it actually works, but I am super confused, because I actually added that line because it didn't work without it and in some other post someone said it would help. xDDD so idk what was wrong before, but anyways, thanks.. – Dejw May 07 '19 at 20:31
  • @wOxxOm I know this is probably too much to ask, but since I am really new to all this, could you refer me to some material that explains why ```return true``` changes this from synchronous to asynchronous? and maybe also what are the differences between these two (I only know some basics). – Dejw May 07 '19 at 20:34
  • See [Chrome Extension Message passing: response not sent](//stackoverflow.com/q/20077487) – wOxxOm May 08 '19 at 04:28

1 Answers1

0

Just deleted return true as @wOxxOm suggested.

Dejw
  • 23
  • 3