firefox扩展切换关闭图标单击

时间:2014-04-25 06:43:41

标签: firefox firefox-addon firefox-addon-sdk

我开发了我的第一个firefox扩展。我的用例(已成功实现为chrome扩展):

  • 注入特定页面的CSS
  • 默认加载:contentscript-on.js
  • 点击图标(icon-on.png / icon-off.png)从contentscript-on.js切换到contentscript-off.js并向后

contentscript-on.js已经适用于页面加载。我搜索过很多东西,为我的用例寻找帮助或示例。有什么想法吗?

非常感谢!

main.js

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

pageMod.PageMod({
  include: "https://app.example.de/dashboard",
  contentScriptFile: [self.data.url("jquery-1.11.0.min.js"), self.data.url("contentscript-on.js")]
});

在我的Chrome扩展程序中,我使用 background.js 来打开/关闭并在脚本之间切换

//toggle = true, because the contenscript-on.js is already loaded on initial loading of the page
var toggle = true;
chrome.browserAction.onClicked.addListener(function(tab) {
toggle = !toggle;
   if(toggle){
//change the icon after pushed the icon to On
    chrome.browserAction.setIcon({path: "icon-on.png", tabId:tab.id});
    //start the content script to hide dashboard
    chrome.tabs.executeScript({file:"contentscript-on.js"});
   }
   else{
//change the icon after pushed the icon to Off
    chrome.browserAction.setIcon({path: "icon-off.png", tabId:tab.id});
    //start the content script to hide dashboard
    chrome.tabs.executeScript({file:"contentscript-off.js"});
    }
});

firefox扩展中是否有类似的方法?

1 个答案:

答案 0 :(得分:1)

PageMod constructor有一个可选的onAttach属性,可将content worker传递给您的函数。可以destroy修改此工作人员以从页面中删除脚本

var contentWorker; // Global (or greater scope) variable
// …
  onAttach: function(worker) {
    contentWorker = worker;
  }

然后,在您的点击监听器中

var tab = contentWorker.tab;
contentWorker.destroy();
contentWorker = tab.attach( {
  contentScriptFile: [self.data.url("jquery-1.11.0.min.js"), self.data.url("contentscript-off.js")]
});

坦率地说,在内容脚本代码中以某种方式附加两者并切换它们可能会更容易

作为旁注,你可以使用一个新的toggle button,它会有一个激活/停用的外观,听起来对你的场景有好处。

相关问题