4

1つのメッセージインターフェイスを使用して、ポップアップとバックグラウンドページの間でメッセージを渡そうとしています(このための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)

何かご意見は?

4

1 に答える 1

9

コード例をコピーし、マニフェストとポップアップ構造で空白を埋めると、エラーなしで完全に機能する拡張機能が得られました。共有したエラーが発生する理由がわかりません。私のコードを試して、エラーを取り除くことができるかどうかを確認してください。

チップ

  • ポップアップにアラートが表示されると、アラートが画面上で点滅し、表示される前に両方とも閉じます。このようなテストのためにコンソールにログインする方がおそらく良いでしょう。

マニフェスト.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 を開いたブラウザ ウィンドウで拡張ボタンをクリックする

exampley.com を開いたブラウザ ウィンドウで拡張ボタンをクリックする

拡張ポップアップのコンソール ログ

拡張ポップアップのコンソール ログ

これは私が使用したファイルのzipですhttp://mikegrace.s3.amazonaws.com/stackoverflow/simple-popup.zip

于 2012-08-17T15:11:34.720 に答える