Skip to content
Advertisement

Google Chrome extensions simple message passing error

I am trying to pass a message between my popup to a background page using the one message interface (I’m using code similar to the one in Google’s example for this).

popup:

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

and this is how I listen (and reply) in background.js:

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

Now when I inspect everything in the console the messages are exchanged ok but I get the following error:

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)

Any thoughts?

Advertisement

Answer

Copying your code example and filling in the blanks with the manifest and popup structure resulted in a fully working extension without errors. Not sure why you are getting the error that you shared. Try my code and see if you can get rid of the error.

Tips

  • Alerts in the popup will result in the alert flashing on the screen and then both will close before you can see them. It is probably better to just log to the console for testing like this.

Example

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);
});

Running Example Screenshots

Clicking extension button with browser window opened to exampley.com

Clicking extension button with browser window opened to exampley.com

Console log of extension popup

Console log of extension popup

Here is a zip of the files I used http://mikegrace.s3.amazonaws.com/stackoverflow/simple-popup.zip

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement