我從我的Chrome擴展的背景腳本中調用以下方法。目標是將消息發送到特定的選項卡,然後調用提供的回調方法和結果。重要的部分是callbackDone
必須是總是在某個時間點調用。如此這般這樣:chrome.tabs.sendMessage回調函數未被調用。爲什麼?
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
}
}
});
}());
}
然後從處理消息的頁面中(可以是注入content script
),我把它處理這樣的:
chrome.runtime.onMessage.addListener(onMessageProc);
function onMessageProc(request, sender, sendResponse)
{
if(request.action == "update01")
{
//Do processing .... that sets `bResult`
sendResponse({result: bResult});
}
}
上述方法工作的很好,除了......我說,有一個頁面,像選項頁面腳本,不處理我update01
消息,相反,它處理自己的消息,例如:
chrome.runtime.onMessage.addListener(onMessageProc);
function onMessageProc(request, sender, sendResponse)
{
if(request.action == "update02") //Note different action ID
{
//Does some other actions...
}
}
在這種情況下,當我爲此選項卡調用第一個sendToTab
方法時,我的callbackDone
永遠不會被調用,即調用chrome.tabs.sendMessage
並立即返回,但其回調函數永遠不會被調用。
那麼我在這裏錯過了什麼?
我不認爲這是所有相關的代碼。 – Xan 2014-09-22 06:37:11
@Xan:你在說什麼? – c00000fd 2014-09-22 08:30:37
我認爲這很重要你的聽衆。它是,但是你的代碼片段就足夠了。 – Xan 2014-09-22 09:10:47