Saturday, September 01, 2007

Window.close() in javascript acts a bit strange…

Javascript is a strange language, it is often confused to be Java, which is very far from right, and the syntax can often be thought to be as consistent as C# or Java. Not the case. Javascript is a strange and weird beast, that when tamed can be a very strong ally. Taming it can however really get on your nerves!

There is one method working on the object window, called close(). Hence it is called using window.close(). It does the simple thing of closing the current browser window. No more, no less.

Well, actually, it does it in a strange way. Have a look at the following code that is executed in body onload. What is going to happen?

Alert("Start");

Windows.close();

Alert("End");


 

I will give you two options:

Option 1:

  1. A dialog window showing "Start" will show.
  2. The current browser window will close.

Option 2:

  1. A dialog window showing "Start" will show.
  2. A dialog window showing "End" will show.
  3. The current browser window will close.

Well?

You would think that option 1 is correct, well, it isn't, the script is executed according to option 2. For some reason, window.close() doesn't actually close the window, it signals it to close and when the onload has reached its end, it is closed. I havn't checked to see if this behavior only happens when executed in onload or if it is the same all over. Be aware though, it might not work as you'd expect!

Gustaf

2 comments:

  1. Visit website for more details.

    ReplyDelete
  2. Interesting page but not right on the point. My original posting concerned the sequencing of the javascript and not confirmations boxes.

    Gustaf

    ReplyDelete