I have the following method that is called from the background script of my Chrome Extension. The goal is to send a message to a specific tab and then call provided callback method with the result. The important part is that the callbackDone
must be always called at some point in time. So it goes as such:
function sendToTab(nTabID, callbackDone)
{
(function()
{
chrome.tabs.sendMessage(nTabID, {
action: "update01"
},
function(response)
{
if(chrome.runtime.lastError)
{
//Failed to send message to the page
if(callbackDone)
callbackDone(nTabID, null); //Page never received the message
}
else
{
//Sent message OK
if(response.result === true)
{
if(callbackDone)
callbackDone(nTabID, true); //Success!
}
else
{
if(callbackDone)
callbackDone(nTabID, false); //Page returns failure
}
}
});
}());
}
Then from within the page that processes the message (can be an injected content script
) I handle it as such:
chrome.runtime.onMessage.addListener(onMessageProc);
function onMessageProc(request, sender, sendResponse)
{
if(request.action == "update01")
{
//Do processing .... that sets `bResult`
sendResponse({result: bResult});
}
}
The above approach works quite well, except... Say, there's a page, like Options page script, that does not process my update01
message and instead, it processes its own message as such:
chrome.runtime.onMessage.addListener(onMessageProc);
function onMessageProc(request, sender, sendResponse)
{
if(request.action == "update02") //Note different action ID
{
//Does some other actions...
}
}
In this case when my first sendToTab
method is called for this tab, my callbackDone
is never called, i.e. chrome.tabs.sendMessage
is invoked and it returns immediately but its callback function is never called.
So what am I missing here?