Content Script Executing Twice?

updated

So did some further debugging, and actually my content script is being called twice, for some reason?

Again this all started with FF52, where it seems some serious backend addon adjustments were made, with little/no patch notes about the content.

Offending code:

Background.js

browser.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) { if (changeInfo.status == "complete" && tab.active) { browser.tabs.executeScript(null, {file: "content_script.js"}); } });

content_script.js

console.log(“You should see me once.”);

I’d recommend searching Bugzilla and if you don’t find any bug report on this issue, create one. The response-time on Bugzilla is surprisingly good.
https://bugzilla.mozilla.org/

I did, and had some pretty odd interactions to start, including having my bug report closed until I basically hand fed them code to duplicate the issue - I even pointed them directly at the piece of code which makes it happen. Then they commented about the cause which didnt make any sense and I could prove didnt make any sense then it went silent. Lets hope it gets fixed. At this point I’m looking at a major feature enhancement to my addons to help get around this.

https://bugzilla.mozilla.org/show_bug.cgi?id=1363949

well if your content script is being called twice, it could be that there is an iframe in the page you are visiting, causing the script to be loaded once for the main window and once for the iframe.

I’ve taken care to ensure that it only activates against a tab and on a tab load event of “complete” - the “executeScript” piece of code only goes once - but for some reason the content script is applied twice. Quite the mystery. It seems to be related to the permissions feature they added in FF52.

Ok, I looked at your code… here is your problem:
You specify a content-script in your manifest, which causes the first execution of content_script.js
Then in background.js, you execute the script again using browser.tabs.executeScript, which causes the second execution. Nothing wrong with Firefox here.

Hey that got it!

I think I understand what happened now and why the bug manifests the way it does.

Thanks for the help!

Not sure why you want to execute the script manually from the background script when you can let the manifest handle it.

I’m not clear on the rules regarding when the manifest will execute the script, but I do understand what my code is doing, so I chose to do it that way.

Is that documented somewhere?

Thanks a ton by the way, thanks to your help I’ve made the addon way more responsive, also did as you suggested and moved the execution into the manifest:)