不调用chrome.tabs.sendMessage回调函数.为什么?

c00*_*0fd 3 javascript google-chrome message-passing google-chrome-extension

我有从Chrome扩展程序的后台脚本调用的以下方法.目标是将消息发送到特定选项卡,然后使用结果调用提供的回调方法.重要的是callbackDone必须始终在某个时间点调用.所以它是这样的:

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
                }
            }
        });
    }());
}
Run Code Online (Sandbox Code Playgroud)

然后从处理消息的页面内(可以注入content script)我处理它:

chrome.runtime.onMessage.addListener(onMessageProc);

function onMessageProc(request, sender, sendResponse)
{
    if(request.action == "update01")
    {
        //Do processing .... that sets `bResult`

        sendResponse({result: bResult});
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的方法效果很好,除了...说,有一个页面,如选项页面脚本,不处理我的update01消息,而是处理自己的消息:

chrome.runtime.onMessage.addListener(onMessageProc);

function onMessageProc(request, sender, sendResponse)
{
    if(request.action == "update02")   //Note different action ID
    {
        //Does some other actions...
    }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,当我sendToTab为此选项卡调用第一个方法时,callbackDone永远不会调用my ,即chrome.tabs.sendMessage调用它并立即返回,但从不调用其回调函数.

那我在这里错过了什么?

Xan*_*Xan 5

你看到了预期的行为.

文档的状态,对于回调函数:

如果指定responseCallback参数,它应该是一个如下所示的函数:

function(any response) {...};

any response
消息处理程序发送的JSON响应对象.如果在连接到指定选项卡时发生错误,则将调用不带参数的回调,runtime.lastError并将设置为错误消息.

sendMessage执行有3种可能的结果.

  1. 有一个听众,它打来电话sendResponse.
    然后,以响应作为参数调用回调.

  2. 有一个监听器,它在没有调用sendResponse(同步或异步)的情况下终止.
    然后,根本不调用回调.

  3. 发送消息时出现某种错误.
    然后,调用回调,不带参数并chrome.runtime.lastError设置.

如果您需要在任何情况下执行回调,则需要在您的侦听器中调用"默认"案例sendResponse.