Tuesday, February 1, 2011

JavaScript differentiate between window refresh and window close events

JavaScript : Differentiate between window refresh and window close events

In software development , once in a while there is a requirement from client , which need to identify difference between window close event and window refresh event, same requirement came to my plate. After google-up too many site, I found there is direct solution to this issue.

Javascript: For JS it is not a different task whether you click on refresh button or clicked on window close(X). For each such activity javascript initiate window.unload event.

This event is raised because , we requested browser to unload the window. It can caused by many ways, for example,

  1. Clicked on link represented by <a> tag
  2. filled the form and tried to submit it.
  3. clicked on refresh button
  4. navigating from website by clicking on window close button.
There is a workaround to differentiate between window close and window refresh, but it will work only on window.onunload event and not on window.onbeforeunload


Code:



<script type="text/javascript">
window.onunload =function(e) {
    if(document.all ? self.screenTop > 9000    : apply())
    {
      //write code what you want to do when clicked on window's close button
    }

function apply()
{
    if (parseInt(navigator.appVersion) > 3)
        var top = navigator.appName == "Netscape" ? window.innerWidth : top.window.document.body.offsetWidth;
    return (top==0 || window.screenX > (top - 25))
}



The reason why this code will not work on window.onbeforeunload is that, window top position will not change when onbeforeunload  event is invoked.

If you have any other solution , please share it.


No comments:

Post a Comment