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.