2011-11-03 125 views
2

我正在做一個FireFox擴展。我有一組URL。我想要的是:使用document.location.href來重定向頁面中的所有URL,然後使用我擁有的XPath計算頁面所具有的元素數量。用document.location.href加載一組URL,然後只在頁面加載時執行JS

問題是,我必須等待頁面加載完成後才執行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中加載的頁面。

我該怎麼做?

+0

你怎麼做*什麼*?在頁面加載之前獲取頁面數據?你不能。或者是「如何等待頁面完成加載」這個問題? –

+0

我只有在頁面加載完成時才需要執行count方法。因此,我如何在我的代碼中顯示的for循環中執行此操作? – Noelia

+0

你真的需要*看*加載頁面嗎?或者你只是試圖從頁面中檢索數據,以便可以針對它運行查詢? –

回答

1

你需要使用過程偵聽read this

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) { } 
} 

如果u需要更多的幫助告訴我。

相關問題