How can I execute something after a new window has

2019-09-08 07:38发布

问题:

I need to close a new window after it fully loads. I have:

my_window=window.open("http://www.yahoo.com", "_blank", "resizable=yes, scrollbars=yes, titlebar=yes, width=500, height=400, top=10, left=10");

I've tried:

my_window.onload = my_window.close();

and

my_window.addEventListener('load', my_window.close(), true);

Neither wait for my_window to finish loading before closing (it closes pretty much immediately).

Secondary question, can I add a timeout to go ahead and close the new window in case the page stalls and for some reason never fully loads?

回答1:

If your window is on the same domain, you can use this:

 my_window.onload = function() {my_window.close();};

or this:

my_window.addEventListener('load', function() {my_window.close();}, true);

You don't use parens after the function name when passing a plain function reference. Using the parens as you were doing causes the function to get executed immediately.

I also added anonymous functions so the my_window context can be preserved until function execution time.

If your window is not on the same domain, then you probably have issues with same origin protections that keep you from accessing the javascript of the other window.