如何防止Firefox SDK内容脚本多次加载? [英] How do I prevent Firefox SDK content scripts from loading multiple times?

查看:92
本文介绍了如何防止Firefox SDK内容脚本多次加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何防止Firefox SDK内容脚本多次加载?我发现的文档和错误报告建议,contentScriptWhen属性应该限制内容脚本的执行次数,但是我发现它们在页面加载中运行两次至15次.

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.

这是我的main.js中的内容:

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

我尝试使用contentScriptWhen属性以及通过在每个脚本上具有'isLoaded'标志来控制此行为-都不能阻止脚本执行多次.

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.

推荐答案

原来,这是

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.

这使我想到了这个问题,作者试图阻止他的插件在iFrame中运行.尤里卡!事实证明,我的插件没有针对同一页面多次初始化",但是page-mod并没有在页面和iFrame之间进行区分.

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.

我使用的解决方案是使用tabs API将我的内容注入到页面上,如下所示:

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

});

发现该问题的另一个版本 ,其中attachTo属性用于指定pageMod.onAttach仅应在顶部窗口中触发,而不是在iframe中触发:

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

这篇关于如何防止Firefox SDK内容脚本多次加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆