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.
<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>
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>
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.