2014-04-25 28 views
0

我开发了我的第一个Firefox扩展。我用例(已成功地为Chrome扩展实现):firexfox扩展开启关闭图标点击

  • 注入特定页面的CSS
  • 默认加载:contentscript-on.js
  • 在点击图标(图标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")] 
}); 

在我的浏览器扩展程序,我用一个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

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,你可以使用它将有一个激活/停用的外观,听起来像它会对你的情况很好。