background image

Weird error reconnecting port in Chrome extension

I was working on my Chrome extension and I ran into an odd error with an exception that wasn’t very descriptive. I couldn’t find the answer on google so here is the solution.

Exception:

Error in event handler for (unknown): The first argument is the receiver and must be an object
Stack trace: TypeError: The first argument is the receiver and must be an object
at TypeError (native)
at Function.propertyNames.forEach.target.(anonymous function) (extensions::SafeBuiltins:19:14)
at EventImpl.dispatchToListener (extensions::event_bindings:395:22)
at Function.propertyNames.forEach.target.(anonymous function) (extensions::SafeBuiltins:19:14)
at Event.$Array.forEach.publicClass.(anonymous function) [as dispatchToListener] (extensions::utils:65:26)
at EventImpl.dispatch_ (extensions::event_bindings:378:35)
at EventImpl.dispatch (extensions::event_bindings:401:17)
at Function.propertyNames.forEach.target.(anonymous function) (extensions::SafeBuiltins:19:14)
at Event.$Array.forEach.publicClass.(anonymous function) [as dispatch] (extensions::utils:65:26)
at dispatchOnMessage (extensions::messaging:304:22)

The issue I ran into had to do with communication between the popup and background page of the extension. I was reconnecting the port when it was disconnected. Basically you might have code like this:

var port;
var listener = function (message) {
    // handle the message
};
var disconnect = function () {
    port = chrome.runtime.connect({name: "foobar"});
    port.onMessage.addListener(listener);
    port.onDisconnect.addListener(disconnect);
};

The issue here is that you aren’t using named functions. It needs to look like this.

var port;
function Listener(message) {
    // handle the message
};
function Disconnect() {
    port = chrome.runtime.connect({name: "foobar"});
    port.onMessage.addListener(Listener);
    port.onDisconnect.addListener(Disconnect);
};

It would be pretty rare that anybody would run into this issue but if you do, you’re welcome.



3 views shared on this article. Join in...

  1. gintaras says:

    thank you, this was bothering me for a couple of hours. Sure is one weird error.

Leave a Reply

Your email address will not be published. Required fields are marked *

Comment

You may use these tags : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>