views:

1085

answers:

4

When we refresh the page (F5, or icon in browser), it will first trigger ONUNLOAD event. When we close the browser (X on right top icon),It will trigger ONUNLOAD event. Now when ONUNLOAD event is triggered, there is no way to distinguish between refresh the page or close the browser. If you have any solution then give me.

A: 
<html>
<body onunload="doUnload()">

<script>

function doUnload()
{

if (window.event.clientX < 0 && window.event.clientY < 0)
 {
   alert("Window closed");
 }
 else
 {
  alert("Window refreshed");
 }
}
</script>
</body>
</html>
Chandan .
Is it work on all the browsers? please give me with the some comments.
ashish bhatt
Thanks friend, But your code is not working FF browser, so Please suggest me another answer.
ashish bhatt
please see the other answer. it should work for you. if it does work, please mark answer as correct so that others know.
Chandan .
+1  A: 

My earlier solution worked for me in IE. window.event would be undefined for browsers other than IE as 'event' is globally defined in IE unlike in other browsers. You would need to supply event as a parameter in case of other browsers. Also that clientX is not defined for firefox, we should use pageX.

Try something like this....should work for IE and firefox this...

<html>
<body>
<script type="text/javascript">

window.onunload = function(e) {
// Firefox || IE
e = e || window.event;

var y = e.pageY || e.clientY;

if(y < 0)  alert("Window closed");
else alert("Window refreshed");

}
</script>
</body>
</html>
Chandan .
thanks Liv 1, I tried this code but it not work properly in Firefox,in this Problem occurs when Tab is closed and refresh button clicked. If you have any other solution then give me please..
ashish bhatt
@renegadeMind, did it work for you?
Chandan .
This technique cannot be used to reliably determine if the browser window has been closed.
wrumsby
A: 

Would anyone have another solution to get this work in FF as I have similar problem and the code above is just working in IE.

Much appreciated for anyone that can help

Thanks

+3  A: 

Unfortunately inspecting the clientY/pageY value of the event, as suggested by some of the answers here, is not a reliable way to determine if the unload event is being fired by as a consequence of the user closing the page.

The reason clientY/pageY is negative when you click the browser's close button is because the close button is positioned above the top of the document (i.e. above pixel 0), but so is the reload button meaning that clicking the reload button will also result in a negative value for clientY/pageY.

Going down the path of inspecting the x co-ordinate of the event is also problematic because the browser close button is not always on the right hand side of the window (e.g. it's on the left in OS X) and because a window can be closed by closing its tab or via the keyboard.

wrumsby