我可以在事件页面中使用sendResponce / onMessage吗? (错误?)

时间:2015-04-22 02:28:53

标签: javascript google-chrome-extension

好像我可以发送消息,但无法接收回复。当我从另一个上下文(弹出窗口,内容脚本等)使用sendMessage时,一切正常。

是bug吗?

事件page.js

(function (chrome, undefined) {
    'use strict';

    chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
        console.info('onMessage: ' + message.method);

        switch (message.method) {
            case 'withResponseAsync':
                setTimeout(function () {
                    sendResponse({some: 'response'});
                }, 1000);
                return true;
                break;

            case 'withResponse':
                sendResponse({some: 'response'});
                break;
        }
    });


    var showResponse = function (response) {
        if (chrome.runtime.lastError) {
            console.error(chrome.runtime.lastError.message);
        }

        console.info(response);
    };

    // ok. onMessage: noResponse
    chrome.runtime.sendMessage({method: 'noResponse'});

    // fail. Could not establish connection. Receiving end does not exist.
    chrome.runtime.sendMessage({method: 'withResponse'}, showResponse);

    // fail. Could not establish connection. Receiving end does not exist.
    chrome.runtime.sendMessage({method: 'withResponseAsync'}, showResponse);

})(chrome);

0 个答案:

没有答案