【问题标题】:Google Chrome extensions simple message passing error谷歌浏览器扩展简单消息传递错误
【发布时间】:2012-08-12 11:23:18
【问题描述】:

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

弹出:

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)

有什么想法吗?

【问题讨论】:

    标签: javascript-events google-chrome-extension


    【解决方案1】:

    复制您的代码示例并使用清单和弹出结构填充空白,从而使扩展完全正常工作且没有错误。不知道为什么您会收到您共享的错误。试试我的代码,看看能不能解决这个错误。

    提示

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

    示例

    manifest.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"]
        }
    }
    

    background.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 的情况下单击扩展按钮

    扩展弹出的控制台日志

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

    【讨论】:

    • +1。最后,该死的截图示例。在 Google 的网站上找不到任何好东西。
    • 谢谢@cbmeeks!这是我回答这个问题的部分动机。
    • 似乎用 console.log() 替换 alert() 会使错误消失。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    • 1970-01-01
    相关资源
    最近更新 更多