简体   繁体   中英

JavaScript window.open() doesn't load window immediately

I have below code. It tries to open a window on line 6. But it keeps loading (shows processing in title bar with blank content in the window). When I step through the code in the debugger and move on line 10 completing execution of line 9, the window finally loads, giving me error

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

I don't get why window.open() does not complete loading web page immediately on window.open() and why it always complete loading when I pass through line 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]);

After reading suggestions online I put following after line 6, but same behavior!!!

targetWin.document.close();

What's going on here? I am debugging in Chrome.

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

This is because window.open is asyncronous . To get the contents of the window, you need to wait for it to be loaded.

From 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.

You could wait for the load event:

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

Alternately, you might wait for the DOMContentLoaded event.

Also, note that this can only be done if same-origin policy is respected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM