在Firefox中检测页面加载完成事件

时间:2010-05-05 07:06:30

标签: javascript events dom firefox-addon

我正在编写一个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调用的网页,此事件会针对一个网页多次触发。

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

1 个答案:

答案 0 :(得分:2)

如果您只想检测页面何时完全加载而不是中间步骤,则更容易监听加载事件,例如(来自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 (...)