Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/440.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我可以在事件页面中使用SendResponse/onMessage吗?(虫子?)_Javascript_Google Chrome Extension - Fatal编程技术网

Javascript 我可以在事件页面中使用SendResponse/onMessage吗?(虫子?)

Javascript 我可以在事件页面中使用SendResponse/onMessage吗?(虫子?),javascript,google-chrome-extension,Javascript,Google Chrome Extension,似乎我可以发送消息,但无法收到响应。当我从另一个上下文弹出窗口、内容脚本等使用sendMessage时,一切都正常 是虫子吗 event-page.js 您不能将消息从一个页面发送到同一个页面,因为这毫无意义。如果您想测试消息传递,请使用两个不同的页面,例如弹出页面和内容脚本。但实际上,我可以发送“简单”消息而无需响应。因为这没有任何意义,我希望重用事件页面其他部分的现有onMessage处理程序,与其他页面中的相同。同样的问题:是的,您可以传递一条简单的消息这一事实可能是一个bug。API通常

似乎我可以发送消息,但无法收到响应。当我从另一个上下文弹出窗口、内容脚本等使用sendMessage时,一切都正常

是虫子吗

event-page.js


您不能将消息从一个页面发送到同一个页面,因为这毫无意义。如果您想测试消息传递,请使用两个不同的页面,例如弹出页面和内容脚本。但实际上,我可以发送“简单”消息而无需响应。因为这没有任何意义,我希望重用事件页面其他部分的现有onMessage处理程序,与其他页面中的相同。同样的问题:是的,您可以传递一条简单的消息这一事实可能是一个bug。API通常不向同一上下文发送消息。
(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);