Click to See Complete Forum and Search --> : Capturing browser close (or closing) event


nauman73
10-10-2003, 04:26 AM
Hi

I am trying to capture the browser close (or closing) event so that I can end the user session whenever the user closes his/her browser window. I have tried 3 different solutions but I still have problems. I am giving the approaches that I have tried.

1. I have tried calling my logout code on the 'onunload' event of the current page. Although this event works when user closes his/her browser window but it has one major problem.

If the user presses refresh button on the browser, this event is fired and the logout code is executed. This is not what I wanted.

2. Another possible solution that I found from web was to execute my logout script on the 'onunload' event of window object. The script declaration is given below.


<script for="WINDOW" event="onunload">

//my logout javascript here

</script>


Again, the script works when I close the browser window but it has the same problem. Even this event gets fired on refresh.

3. I tried to place a check in my javascript by writing this piece of code.



if (window.closed)
{
// do the logout
}



I was expecting that 'window.closed' will return 'true' when the user closes borwser window and I would be able to execute my logout code only when I get 'true'. I thought that 'window.closed' will return false on refresh and the logout code will not be executed.

If all wishes could come true... :) 'Window.closed' returns false even if I close the browser window. So this solution disables the logout alltogether :)

Any ideas? Will appreciate any help.

Thanks.

Nauman

kanakaprasad
10-10-2003, 08:27 AM
well! just imagine what if some one makes the browser not to close unless u shut down the IE. and thats the reason why browser close event is not given to control. u understood what i mean. so u better leave the browser as it is. its a common problem ever where and no solution for that. if u put any alerts its kinda annoying to the user. good luck

jbergthorson
10-10-2003, 10:48 AM
what if you did this:
onUnload open a new window that contains your logout script.

onLoad of the new window, use:
setTimeout("pageClosedTest()", 1000);

then:

function pageClosedTest(){
var address = document.location.href.substr(0,document.location.href.length-lengthOfThisPageFileName);

if(opener.document.location.href==address+"yourPage.html")
//page was just refreshed do nothing but close this window
else
theLogoutScript();
window.close();
}

Opens another window, but if you set the size and loc to 0's it will be up in the top left corner and really small and open for only 1 second or whatever you put in your setTimeout as a delay.

it's an idea if you really want to do the logout thing with allowing refreshes.

jason

krishnendra
09-14-2006, 12:22 AM
try this inside ur javascript function of unload

if(window.screenLeft >screen.width){
//browser is closed
}
else{
//refresh
}