0

I'm a bit confused by the usage of sendResponse (as in chrome.runtime.onMessage.addListener) and chrome.tabs.sendMessage.

What I'm trying to do is that I want to send a message from the content script to the background, and the background will respond with some appropriate message. The code that I have is as follows.

In content script:

var currentHost = window.location.host;
chrome.runtime.sendMessage({ type: 'getUsageTime', host: currentHost }, function (res) {
    console.log(res);
});

In background:

function onMessage (message, sender, sendResponse) {
  if (message.type === 'getUsageTime') {
    console.log('Getting the usage time for ' + message.host);
    sendResponse({ usageTime: usageTime });
    return true;
  }
}

chrome.runtime.onMessage.addListener(onMessage);

What this does is that the content script will send a message to request the usage time of that particular host. According to my current understanding of what sendResponse does, the code above (in particular, the line console.log(res)) should be able to log the response message. However, this is not as expected and that line of code does nothing (and probably isn't even reached).

Moreover, if I try to send a message in the background by chrome.tabs.sendMessage and supplying the appropriate tab id, that works (as expected) but it's too troublesome to fire another sendMessage in the background this way.

What exactly is happening here? What are the differences between sendResponse and chrome.tabs.sendMessage? Why is my code not working?

Any help very much appreciated.

hsiaomichiu
  • 582
  • 5
  • 21
  • At the first glance, your code should work. Where does `usageTime` come from? Have you simplified the code here? – Xan Jan 11 '15 at 16:05
  • `usageTime` is basically a string used to identify the type of message I'm sending. Oh, you have reminded me that I'm placing `sendResponse` inside another `chrome.storage.local.get` callback. If I move it out of that callback, it would work. But why is this so? – hsiaomichiu Jan 11 '15 at 16:33
  • 1
    Aha. Then, let me find the canonical question.. – Xan Jan 11 '15 at 16:34
  • Exactly the solution I'm looking for. Thank you. (Actually I browsed through that page several times but I didn't realise that it is the same problem I'm facing...) – hsiaomichiu Jan 11 '15 at 16:43

0 Answers0