获取特定选项卡的内容(Firefox插件开发)

Get the contents of a particular tab (Firefox add-on development)

本文关键字:Firefox 插件 开发 选项 获取      更新时间:2023-09-26

我正在开发一个Firefox插件,有了它,我需要监视特定站点的内容并对DOM更改做出反应。目前,我正在使用gBrowser.contentDocument.getElementsByClassName("class")的组合,并将DOMSubteeeModified事件附加到它。但我注意到,它只有在选项卡处于活动状态时才有效。当我使用另一个选项卡时,非活动选项卡中的DOM发生了变化,它就不起作用了。我该怎么解决这个问题?Firefox的MDN相当分散(有时过时),这对新手来说是非常令人沮丧的。

下面是我正在做的事情的简化版本:

var MyExtension = {
    init() : function() {
        if("gBrowser" in window) {
            gBrowser.addEventListener("DOMContentLoaded", function(e){this.onPageLoad(e);},false);
        },
   onPageLoad: function(e) {
       var doc = e.originalTarget;
       if((/http://xxxx.xyz/v/[0-9a-z]/).test(doc.location.href)) {
           MyExtension.XXX.handler(e);
       }
       e.originalTarget.defaultView.addEventListener("unload", function(e){MyExtension.onUnload(e);}, false);
   },
   onUnload: function(e) {
       if((/http://xxxx.xyz/v/[0-9a-z]/).test(e.originalTarget.location.href)) {
           //remove listeners and nullify references to dom objects
   }
};
MyExtension.XXX = {
    handler : function(e) {
        //get dom element with gBrowser.contentDocument.getElementsByClassName("class");
        //bind DOMSubtreeModified listener, attach a function to handle the event
    }
};
window.addEventListener("load", function(e) {
    window.removeEventListener("load", load, false);
    MyExtension.init();
}, false);

这是我所遵循的技术,使用gBrowser.selectedBrowser文档在这里

var MyExtension = {
    tab : null, //<---- added this line
    init() : function() {
        if("gBrowser" in window) {
            gBrowser.addEventListener("DOMContentLoaded", function(e){this.onPageLoad(e);},false);
    },
    onPageLoad: function(e) {
       var doc = e.originalTarget;
       if((/http://xxxx.xyz/v/[0-9a-z]/).test(doc.location.href)) {
           this.tab = gBrowser.selectedBrowser; //<--- GET REFERENCE TO CURRENT TAB
           MyExtension.XXX.handler(e);
       }
       e.originalTarget.defaultView.addEventListener("unload", function(e){MyExtension.onUnload(e);}, false);
    },
    onUnload: function(e) {
       if((/http://xxxx.xyz/v/[0-9a-z]/).test(e.originalTarget.location.href)) {
           //remove listeners and nullify references to dom objects
       }
    };
    MyExtension.XXX = {
        handler : function(e) {
        //get dom element
        MyExtension.tab.contentDocument.getElementsByClassName("class"); //<--- GET CONTENT DOCUMENT INSIDE DESIRED TAB
        //bind DOMSubtreeModified listener, attach a function to handle the event
    }
};