Email conversation
From | Fran Johnson |
To | Me |
Subject | How to detect window.close event with Javascript |
Date | 21 September 2004 20:41 |
Hi Mark,
I found your site when trying to find an answer to the problem of detecting
window closing with Javascript (in IE).
What I want to detect is when the window closes, not when it is redirected
or refreshed.
The only answer that comes close is the code that I found at this website:
http://xxxxxxxxxxxxx.xxx/xxxxxx/xxxxxxxxxx/xxxxxxx/xxxx/xx/xx/xxxxx.xxxx
So here is my adaptation of the code that I found, however sometimes the
logout function is getting called even when the window is not being closed.
function logout()
{
location.replace('logout.jsp');
}
// Catch window closings and logout
window.onbeforeunload = function(){
if((window.event.clientX<0) || (window.event.clientY<0)) logout();
}
If you have an answer to this it will be very much appreciated!
Fran Johnson
From | Me |
To | Fran Johnson |
Subject | Re: How to detect window.close event with Javascript |
Date | 21 September 2004 21:30 |
Fran,
This is a difficult one. The trouble is that to JavaScript, all of these
events (closing, reloading, redirecting, etc.) are the same thing. So the
script has no way to know which is which.
The code you have is a hack. And it is not a good hack either. It almost
certainly will get false positives, and definitely will not work cross
browser. It may well also fail in different versions of IE. Throw it away,
it's not worth it :)
A quick bit of research did come up with a useful trick though.
Hold the page in a frameset. Attach the onunload event to the frameset page,
_not_ the page inside it. When they close the window, it will fire. If they
click a link in the page, it will not. If you reload the page with script,
it will not fire. If they right click and refresh, it will not fire. If
they have a refresh or reload button (if you did not hide it using
window.open), it _will_ fire. There is nothing that you can do to prevent
that, except hiding the button using window.open to open the window without
the menu bar. Usefully, this technique also works fully cross browser.
Hope this is useful
Mark 'Tarquin' Wilton-Jones - author of http://www.howtocreate.co.uk/
From | Fran Johnson |
To | Me |
Subject | Re: How to detect window.close event with Javascript |
Date | 21 September 2004 22:11 |
Mark, you are so kind to give me these suggestions, and so quick with your
response. I will consider the frameset option. Thank you very much!!
Fran