Firefox附加SDK:在所有打开的页面和任何新页面中运行内容脚本

时间:2015-03-26 01:57:21

标签: javascript firefox-addon-sdk

我们说我有一个简单的内容脚本,例如window.alert("Hey there"); console.log("Content script")

我无法在SDK中找到一种方法,使脚本在每个打开的窗口和选项卡上运行,并允许它在每个新窗口上运行。

使用选项卡,脚本将在所有新打开的窗口和选项卡上运行,但会忽略已加载的那些:

require("sdk/tabs").on("ready", function(tab) {
  tab.attach({
  contentScript: 'window.alert("Hey there");'
  });
});

使用带有" *"的包含模式的pagemod,该脚本将仅在具有非空白URL的窗口和选项卡上运行:

require('sdk/page-mod').PageMod({
  include: "*",
  contentScriptWhen: "ready",
  contentScript: 'window.alert("AAAAAAAAA");'
});

我可能遗漏了一些简单的东西,这些东西可以让我正确地实现这一点。在所有打开和新页面上调用内容脚本的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

您正在寻找attachTo属性。

require('sdk/page-mod').PageMod({
  include: "*",
  contentScriptWhen: "ready",
  contentScript: 'window.alert("AAAAAAAAA");',
  attachTo: ['existing', 'top', 'frame'] 
});

示例中的内容脚本将被注入

  • 现有标签
  • 顶级标签(包括将来会打开的标签)
  • 任何上述标签类型中的iframe

Mozilla开发人员文档https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/page-mod#PageMod%28options%29

答案 1 :(得分:0)

如果要在about:blank和about:newtab中运行内容脚本,请尝试将tab url更改为大写并重新加载选项卡。 about:blank和about:Blank是同一页面。和内容脚本可以在about:Blank。

中运行
tabs.on(
    'ready',function(tab) {
        // if tab url is about:blank, change url to 'about:Blank', and reload when tab ready.
        if(Boolean(tab.url.match(/^about\:blank$/))){
            tab.url = 'about:Blank'
            tab.reload()
        }
        // run content script in about:Blank and about:NewTab
        else if(Boolean(tab.url.match(/^about\:(?:Blank|NewTab)$/))){
            var worker = tab.attach(
                {
                    contentScript:'console.log("run content script in '+tab.url+'")'
                }
            )
        }
    }
)

tabs.on(
    'open',function(tab) {
        // if tab url is about:newtab, change url to 'about:NewTab', and reload when tab open.
        if(Boolean(tab.url.match(/^about\:newtab$/))){
            tab.url = 'about:NewTab'
            tab.reload()
        }
    }
)
相关问题