How do I prevent Firefox SDK content scripts from loading multiple times?

元气小坏坏 提交于 2020-01-14 03:30:13

问题


How do I prevent Firefox SDK content scripts from loading multiple times? The docs and a bug report I found suggest the contentScriptWhen property should limit the number of times my content scripts are executed, yet I see them running anywhere from twice to 15 times in a page load.

Here's what's in my main.js:

var data = require("sdk/self").data;
var tabs = require('sdk/tabs');

var pageMod = require('sdk/page-mod');
pageMod.PageMod({
    include: ['*'],
    contentScriptWhen: "ready",
    contentScriptFile: [data.url("extBootstrapper.js"), data.url("extContent.js")],
    onAttach: function(worker) {
       //handlers for AJAX and changing preferences, etc
       ...
});

I've tried controlling this behavior with the contentScriptWhen property, as well as by having an 'isLoaded' flag on each script - neither prevents the scripts from executing multiple times.


回答1:


Turns out this was a duplicate of this question, which, naturally, only turned up in search results a couple of hours after I had posted its duplicate. Go figure.

It lead me to this question in which the author was attempting to prevent his addon from running in iFrames. Eureka! Turns out my addon wasn't "initializing" multiple times for the same page, but page-mod doesn't make distinctions between pages and iFrames.

The solution I used was to use the tabs API to inject my content onto the page, like so:

var data = require("sdk/self").data;
var tabs = require('sdk/tabs');

tabs.on('ready', function(tab) {
     var worker = tab.attach({
          contentScriptOptions: {},
          contentScriptFile: [data.url('myScript.js')]
     });

     // now set up your hooks:        
     worker.port.on('someKey', function(data) {
          //do whatever with your data
     });

});

Turns out another version of this question also existed, in which the attachTo property is used to specify that pageMod.onAttach should only be fired on the top window, rather than iframes:

var data = require("sdk/self").data;
var page = require('sdk/page-mod');

page.PageMod({
     match:['*'],
     contentScriptOptions: {},
     contentScriptFile: [data.url('myScript.js')],
     attachTo: 'top',
     onAttach: function(worker) {
         //set up hooks or other background behavior
     },
});


来源:https://stackoverflow.com/questions/26149431/how-do-i-prevent-firefox-sdk-content-scripts-from-loading-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!