使用document.location.href加载一组URL's,然后仅在加载页面时执行JS

Load a set of URL's with document.location.href and then execute JS only if the page was loaded

本文关键字:加载 然后 JS 执行 href location document 使用 URL 一组      更新时间:2023-09-26

我正在做一个FireFox扩展。我有一个URL数组。我想要的是:用document.location.href重定向我拥有的所有URL的页面,然后,用我拥有的XPath,计算页面拥有的元素数量。

问题是,我必须等待页面加载完成,然后才能使用XPath执行count方法。这是我的代码:

var actualResult = 0;
actualResult = content.document.evaluate('count('+taskModeler.ui.getStatus()+')', content.document, null, XPathResult.NUMBER_TYPE, null).numberValue; 
for(var i=0; i<taskModeler.ui.getPageContent().length;i++) {
    content.document.location.href = taskModeler.ui.getPageContent()[i].getAttribute("href");
   //only if the page was loaded execute the next line
   actualResult+=content.document.evaluate('count('+taskModeler.ui.getStatus()+')',
       content.document, null, XPathResult.NUMBER_TYPE, null).numberValue; 
}

getPageContent()返回一个数组,其中包含URL的的集合。对于每个URL,我都必须加载页面以访问文档,然后计算返回XPath的次数。但是,如果页面没有加载,count方法不起作用,因为返回的是实际页面的结果,而不是content.document.location中加载的页面。

我该怎么做呢?

您需要使用进度侦听器读取此

const STATE_START = Components.interfaces.nsIWebProgressListener.STATE_START;  
const STATE_STOP = Components.interfaces.nsIWebProgressListener.STATE_STOP;  
  var myListener =  
 {  
 QueryInterface: function(aIID)  
 {  
  if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||  
   aIID.equals(Components.interfaces.nsISupportsWeakReference) ||  
   aIID.equals(Components.interfaces.nsISupports))  
 return this;  
 throw Components.results.NS_NOINTERFACE;  
  },  
 onStateChange: function(aWebProgress, aRequest, aFlag, aStatus)  
 {  
 // If you use myListener for more than one tab/window, use  
 // aWebProgress.DOMWindow to obtain the tab/window which triggers the state change  
 f (aFlag & Components.interfaces.nsIWebProgressListener.STATE_IS_DOCUMENT) { 
 {  
     if(aFlag & STATE_STOP)  
 {  
   // This fires when the load page finishes  
 }  
 }  
     },  
 onLocationChange: function(aProgress, aRequest, aURI)  
  {  
  // This fires when the location bar changes; that is load event is confirmed  
  // or when the user switches tabs. If you use myListener for more than one tab/window,  
  // use aProgress.DOMWindow to obtain the tab/window which triggered the change.  
  },  
 // For definitions of the remaining functions see related documentation  
 onProgressChange: function(aWebProgress, aRequest, curSelf, maxSelf, curTot, maxTot) { },  
 onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage) { },  
 onSecurityChange: function(aWebProgress, aRequest, aState) { }  
 }  

如果你需要更多的帮助,告诉我。