1

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?

Jack Hillard
  • 576
  • 10
  • 25

1 Answers1

0

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Wouldn't that close `window`? Assigning `= my_window.close;` would assign `close` without a _context_ to the `onload` so if called it is called in the default context (`window`). Or is this a special case? – t.niese Oct 04 '13 at 05:48
  • @t.niese - yes, I modified my code to be sure the right context is used. – jfriend00 Oct 04 '13 at 05:50
  • Will this wait for the window to fully load then close before executing any more script below the line `my_window.onload = function() {my_window.close();};`? I want to open another new window but it has to be after the first one has fully loaded then closed. Unfortunately, I don't have access to the server to test this at the moment since they have to all be on the same domain. – Jack Hillard Oct 04 '13 at 05:57
  • @JackHillard - no, it won't wait. Javascript in the current window will continue to run. There is no ability to "block and wait" in javascript other than a few simple functions like `alert()`. `my_window.close()` will be called some time in the future when `my_window` finishes loading. – jfriend00 Oct 04 '13 at 20:15