Javascript 为什么这个contentscript在firefox插件中运行不同的时间?

Javascript 为什么这个contentscript在firefox插件中运行不同的时间?,javascript,firefox-addon,code-injection,Javascript,Firefox Addon,Code Injection,我正在学习如何创建Firefox插件。我想做一个简单的插件,它将在页面中插入脚本。我已经阅读了文档,但是我不能解决这个问题 在cfx运行日志中,我可以看到它在同一个页面中多次运行脚本,而它应该只运行一次 main.js var pageMod = require('sdk/page-mod') var data = require('sdk/self').data pageMod.PageMod({ include: ['*'], contentScriptWhen: 'end',

我正在学习如何创建Firefox插件。我想做一个简单的插件,它将在页面中插入脚本。我已经阅读了文档,但是我不能解决这个问题

在cfx运行日志中,我可以看到它在同一个页面中多次运行脚本,而它应该只运行一次

main.js


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

pageMod.PageMod({
  include:  ['*'],
  contentScriptWhen: 'end',
  contentScriptFile: data.url('starter.js')
})
starter.js


var script = document.createElement('script');

script.id = 'i-inject';
script.type = 'text/javascript';
script.src = 'http://localhost:8888/injectme.js';
document.getElementsByTagName('head')[0].appendChild(script);
console.log('injected');
您看到这个console.log('injected')了吗?我可以看到,当我运行cfx时,它会在控制台中打印5次,每次我重新加载页面时都会打印。我不理解那种行为


非常感谢您的帮助:)

我刚刚问完同一个问题,因为某种原因,多次搜索直到现在都没有找到这个问题

您发布的关于iFrames的链接让我找到了这个解决方案,它似乎运行良好

在Firefox中,iFrame仍然是页面,默认情况下SDK不会区分iFrame和顶级页面,导致内容脚本附加到满足pageMod“匹配”要求的任何加载页面(或iFrame)。您可以使用选项卡来插入所需的脚本和数据,而不是使用page mod

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

});
或者,您可以修改PageMod的行为,使其仅应用于顶部页面,这将阻止它在页面上的任何iFrame中运行

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

pageMod.PageMod({
    match: [*],
    attachTo: ["top"],
    contentScriptOptions: {},
    contentScriptFile: [data.url('myScript.js')],
    onAttach: function(worker) {
        //function body
    }
});

有关如何进一步控制页面修改行为的更多详细信息,请参见他们的

您确定它在同一页面中运行了5次,或者对于页面可能包含的四个iFrame中的每一个,只运行一次,然后再运行一次吗?您好,我没有想到iFrame。你的评论让我想到了这个问题:我想我必须试着用这种方式来解决它。如果你愿意,你可以提出一个答案,我会投票表决。Chrome扩展不这样做,我以为会是一样的,谢谢:)嗨。谢谢你的回答。我也这样做了。但问题是为什么它会运行多次。如果你能用理由(实际上@nmaier所说的)完成你的答案,我会接受的。