2017-02-12 340 views
0

我有下面的代碼。它嘗試在第6行打開一個窗口。但它會一直加載(在窗口中顯示空白內容的標題欄中的處理)。當我步調試器中的代碼,並在完成9號線的線執行10移動,窗口最後裝入,給我的錯誤JavaScript window.open()不立即加載窗口

Uncaught TypeError: Cannot read property '0' of null on line 9.

我不知道爲什麼window.open()沒有完成加載網頁上立即window.open()爲什麼它總是完全加載,當我經過管線9

var pageURL='url'; 
var w=500; 
var h=500; 
var left = (screen.width/2)-(w/2); 
var top = (screen.height/2)-(h/2); 
var targetWin = window.open (pageURL, "_blank",'toolbar=no, location=no,directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left); 
var windowStr = targetWin.document.documentElement.innerHTML; 
var divMatch = windowStr.match(/someregex/); 
console.log(divMatch[0]); 

在線閱讀建議後我把線6條,但相同的行爲後,下面的!

targetWin.document.close(); 

這是怎麼回事嗎?我在Chrome中進行調試。

+0

在投票之前,我會明白任何評論...我知道這可能不是工作代碼......但人們的經驗仍然可以交談......如果真的需要一個虛擬代碼...那麼我必須準備它並看看它是否給出了相同的行爲。但是,請在下投票前要求虛擬代碼是絕對需要的。 – anir

+0

@wOxxOm你能解釋一下嗎?如果它是關於CORS的東西,那麼它根本不應該加載,甚至不會在第9行之後對嗎? – anir

回答

3

I don't get why window.open() does not complete loading webpage immediately

這是因爲window.openasyncronous。要獲取窗口的內容,您需要等待它被加載。

MDN

Note that remote URLs won't load immediately. When window.open() returns, the window always contains about:blank . The actual fetching of the URL is deferred and starts after the current script block finishes executing. The window creation and the loading of the referenced resource are done asynchronously.

你可以等待load事件:

var targetWin = window.open (...); 
targetWin.addEventListener('load', function() { 
    // Continue doing stuff here. 
}); 

或者,你可能會等待DOMContentLoaded事件。

此外,請注意,只有在遵循same-origin policy的情況下才能完成此操作。