onMessage listener is installed multiple times in a content script - why?!

2,674 views
Skip to first unread message

Jakub Holy

unread,
Mar 31, 2014, 9:31:28 AM3/31/14
to chromium-...@chromium.org
While troubleshooting my extension, I have discovered that a content script is executed repeatedly so having

chrome.runtime.onMessage.addListener(function(message, sender, sendResponseFn){ ...}

in it will install the listener repeatedly and will thus lead to multiple invocations of the listener. I haven't however seen this mentioned in the docs and can see that sample extensions do exactly this, i.e. have addListener at top level of the content script.

I work around the problem by using

var initialized;
if (typpeof initialized === 'undefined') {
  initialized = true;
  chrome.runtime.onMessage.addListener(function(message, sender, sendResponseFn){ ...}
}

but I would like to understand if this is some error on my part or of the docs are outdated or what is going on.

I am using Chrome  33.0.1750.154 m

thank you!

Xan

unread,
Apr 3, 2014, 9:42:57 AM4/3/14
to chromium-...@chromium.org
If you inject the content script several times, it will execute the addListener several times, and as the name suggests it will add, and not replace, a function that will be called.
Note that the sample extension creates a new tab before injecting the script, so it doesn't happen.

See the Event documentation. If there is a risk that addListener will be executed several times, you can check hasListeners instead of having your own flag.
Reply all
Reply to author
Forward
0 new messages