如何使firefox扩展在指定的域上运行js

时间:2014-07-06 11:10:34

标签: javascript firefox firefox-addon

我之前制作了一个Chrome扩展程序,它只在一个域上运行(比如说test.com),并在打开该域后立即执行我的JS文件(比如说my.js)。我希望将它移植到Firefox。

如何做到这一点?我是Firefox附加组件开发的新手。我尝试从Firefox文档阅读,但无法理解。

2 个答案:

答案 0 :(得分:1)

它是自举插件还是叠加插件?

无论如何....尝试On page load

上给出的代码
var myExtension = {
    init: function() {
        // The event can be DOMContentLoaded, pageshow, pagehide, load or unload.
        if(gBrowser) gBrowser.addEventListener("DOMContentLoaded", this.onPageLoad, false);
    },
    onPageLoad: function(aEvent) {
        var doc = aEvent.originalTarget; // doc is document that triggered the event
        var win = doc.defaultView; // win is the window for the doc
        // test desired conditions and do something
        // if (doc.nodeName != "#document") return; // only documents
        // if (win != win.top) return; //only top window.
        // if (win.frameElement) return; // skip iframes/frames
        alert("page is loaded \n" +doc.location.href);
    }
}
window.addEventListener("load", function load(event){
    window.removeEventListener("load", load, false); //remove listener, no longer needed
    myExtension.init();  
},false);

我自己做的是(例如仅在imdb.com上运行):

let doc = aEvent.originalTarget;
if (doc.location.hostname.match(/\.imdb\.com$/)) {
    // this is the page that you want to run on
}

答案 1 :(得分:0)

如果你在Firefox上使用Addon-SDK,你几乎只需要page-mod module,它会在域/ URL与page-mod期望的内容匹配时执行脚本。检查一下,以及内容脚本如何与插件通信。