javascript - 谷歌浏览器扩展简单消息传递错误

标签 javascript google-chrome-extension dom-events

我正在尝试使用一个消息界面在弹出窗口之间传递一条消息到背景页面(我正在使用类似于谷歌示例中的代码)。

弹出:

chrome.extension.sendMessage( {msg: "this is popup's msg"}, function(b){
    alert('this is popups callback func' +b.backgroundMsg);
});

这就是我在 background.js 中聆听(和回复)的方式:
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
    sendResponse({backgroundMsg: "this is background msg"});
});

现在,当我检查控制台中的所有内容时,消息交换正常,但出现以下错误:
Error in event handler for 'undefined': Cannot call method 'disconnect' of null TypeError: Cannot call method 'disconnect' of null
    at chromeHidden.Port.sendMessageImpl (miscellaneous_bindings:285:14)
    at chrome.Event.dispatch (event_bindings:237:41)
    at Object.chromeHidden.Port.dispatchOnMessage (miscellaneous_bindings:250:22)

有什么想法吗?

最佳答案

复制您的代码示例并使用 list 和弹出结构填充空白会导致完全正常工作的扩展没有错误。不知道为什么您会收到您共享的错误。试试我的代码,看看你能不能摆脱这个错误。

提示

  • 弹出窗口中的警报将导致警报在屏幕上闪烁,然后两者都会在您看到它们之前关闭。最好只登录到控制台进行这样的测试。


  • 例子

    list .json

    {
        "name": "Stackoverflow Message Passing Example",
        "manifest_version": 2,
        "version": "0.1",
        "description": "Simple popup with message passing for Stackoverflow question",
        "browser_action": {
            "default_popup": "popup.html"
        },
        "background": {
            "scripts": ["background.js"]
        }
    }
    

    背景.js

    chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
        sendResponse({backgroundMsg: "this is background msg"});
    });
    

    popup.html

    <html>
        <head>
            <script src="popup.js"></script>
            <style type="text/css" media="screen">
                body { width: 100px; height: 100px; }
            </style>
        </head>
        <body>
            <p>Check the console</p>
        </body>
    </html>
    

    popup.js

    chrome.runtime.sendMessage( {msg: "this is popup's msg"}, function(b){
        console.log('this is popups callback func ' + b.backgroundMsg);
    });
    

    运行示例截图

    在浏览器窗口打开到 exampley.com 的情况下单击扩展按钮

    Clicking extension button with browser window opened to exampley.com

    扩展弹出的控制台日志

    Console log of extension popup

    这是我使用的文件的 zip http://mikegrace.s3.amazonaws.com/stackoverflow/simple-popup.zip

    关于javascript - 谷歌浏览器扩展简单消息传递错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11981606/

    相关文章:

    javascript - CSS/JS : Height peculiarity in Chrome

    javascript - window.postMessage 的 DOM 异常 12

    Javascript dispatchEvent - 如何更改 eventArgs

    javascript - 为什么我的 EventListener 被调用两次?

    javascript - 我如何将变量从 PHP 传递到我的 html 文本,以便它根据值而变化

    c# - getJSON 函数未执行

    javascript - 如何使用我的 Chrome 扩展文件分发 OAuth2 客户端 ID?

    javascript - JavaScript 事件监听器是否自动清理?

    javascript - 如何等到 onload 事件在 JavaScript 中完成它的工作?

    javascript - 更改为在小数点后添加 2 位数字