1

I have a background page and a content script. the content script has this code:

chrome.runtime.sendMessage({ getSetting: { setting: "hideAuth" } }, function (hide) {
    // this should be executed after 'respond(setting)' in the backgroud page
});

The background page has this code:

chrome.runtime.onMessage.addListener(function (msg, sender, respond) {
    if (msg["getSetting"]) {
        chrome.storage.sync.get(msg.getSetting.setting, function (setting) {
            respond(setting); // this should callback to the content script
            });
        });
    }
});

However, the response callback in the content script is never executed. I've tried the run-around of querying the current tab and sending a message back manually but the tab still does not receive the message. Has anyone dealt with this before? Is there another way to to do this?

Stephen Collins
  • 3,523
  • 8
  • 40
  • 61

1 Answers1

1

Since you are calling the respond function asynchronously (i.e. inside the callback of chrome.storage.sync.get, you should add return true; in your onMessage listener callback:

chrome.runtime.onMessage.addListener(function (msg, sender, respond) {
    ...
    return true;
});

Quoting the docs:

This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called).

gkalpak
  • 47,844
  • 8
  • 105
  • 118
  • Well that works like a charm, but now I'm getting `cannot call method 'disconnect' of null` from the `extensions::event_bindings` code. Is there a way to manually disconnect before that code catches it? – Stephen Collins Jan 09 '14 at 00:08
  • Where are you calling disconnect ? `disconnect` is meant for persistent connections only, not for simple, one-time message passing. You don't need it - just use the code above (nothing more is needed). – gkalpak Jan 09 '14 at 11:21
  • That's just the thing. I'm not. It's getting called by some internal code that I don't control. Which means I'm doing something wrong. – Stephen Collins Jan 09 '14 at 12:17
  • This is strange because I ran the same code (from above) and there was no such error. If you could post the whole code somewhere, I could take a look. Posting the exact stack trace in its entirety might help as well. – gkalpak Jan 09 '14 at 12:26
  • Try attaching a debugger to it. I just realized it only occurs when I hit a breakpoint within the content script's response callback. – Stephen Collins Jan 09 '14 at 12:37