分享

javascript – 在Firefox中检测页面加载已完成的事件

 印度阿三17 2019-07-05

我正在编写一个Firefox插件,在网页完全加载后做了一些事情.我现在的代码是

var target = this;
    const STATE_STOP = Components.interfaces.nsIWebProgressListener.STATE_STOP;
    const STATE_IS_WINDOW = Components.interfaces.nsIWebProgressListener.STATE_IS_WINDOW;
    const STATE_IS_DOCUMENT = Components.interfaces.nsIWebProgressListener.STATE_IS_DOCUMENT;
    const locationChangeListener = {
        onStatusChange: function(){},
        onProgressChange: function(){},
        onLocationChange: function(aWebProgress, aRequest, aLocation){},
        onStateChange: function(aWebProgress, aRequest, aFlag, aStatus){
            if((aFlag & STATE_STOP) && (aFlag & STATE_IS_WINDOW)){


                //Do something in here


            }
        },
        onSecurityChange: function(){}
    };
    gBrowser.addProgressListener(locationChangeListener);

它工作正常.但有时,例如使用AJAX调用的网页,此事件会针对一个网页多次触发.

有没有办法检测网页是否完全加载?

解决方法:

如果您只想检测页面何时完全加载而不是中间步骤,则更容易监听加载事件,例如(代码来自https://developer.mozilla.org/en/Code_snippets/Tabbed_browser):

function examplePageLoad(event) {
  if (event.originalTarget instanceof HTMLDocument) {
    var win = event.originalTarget.defaultView;
    if (win.frameElement) {
      // Frame within a tab was loaded. win should be the top window of
      // the frameset. If you don't want do anything when frames/iframes
      // are loaded in this web page, uncomment the following line:
      // return;
      // Find the root document:
      win = win.top;
    }
  }
}

// do not try to add a callback until the browser window has
// been initialised. We add a callback to the tabbed browser
// when the browser's window gets loaded.
window.addEventListener("load", function () {
  // Add a callback to be run every time a document loads.
  // note that this includes frames/iframes within the document
  gBrowser.addEventListener("load", examplePageLoad, true);
}, false);

...
// When no longer needed
gBrowser.removeEventListener("load", examplePageLoad, true);
...

gBrowser是主要firefox窗口中的全局变量(如果你的代码是从browser.xul的叠加层运行的,你应该看到它).如果不是(例如在侧栏中运行),您可以获得对主窗口的引用:

var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                       .getInterface(Components.interfaces.nsIWebNavigation)
                       .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
                       .rootTreeItem
                       .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                       .getInterface(Components.interfaces.nsIDOMWindow);

mainWindow.gBrowser.addEventListener (...)
来源:https://www./content-1-300551.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多