Identifying Between Refresh And Close Browser Actions

Viewed 106447

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.

13 Answers

Maybe someone is still searching for an answer...

You can use SessionStorage for that! SessionStorage is not cleared when the page is reloaded but when it is closed. So basically you could set a key/value pair when the page is loaded, but before that you check if the key/value pair exists. If it does exists it means that the page was reloaded, if not it means that the user opened the page for the first time or in a new tab.

if (sessionStorage.getItem('reloaded') != null) {
    console.log('page was reloaded');
} else {
    console.log('page was not reloaded');
}

sessionStorage.setItem('reloaded', 'yes');

This way you can doStuff() with the onunload event (user leaves the page), and otherStuff() if the key/value pair is set (user reloaded the page).

This is a huge hack with some limitations but it will work in most practical cases.

So if you just need something that works when users use the ctrl+r or cmd+r shortcut, you can keep track of whether r is pressed when whatever you need to do upon reload/close gets run.

Simply create keydown and keyup event listeners that toggle a rDown variable.

let rDown = false;
window.addEventListener("keydown", event => {
    if (event.key == 'r')
        rDown = true;
})
window.addEventListener("keyup", event => {
    if (event.key == 'r')
        rDown = false;
})

Then you have your "onunload" event listener where the listener function has an if statement checking if rDown is true.

window.addEventListener("onunload", () => {
    if (!rDown) {
        // code that only gets run when the window is closed (or
        // some psychopath reloads by actually clicking the icon)
    }
});

Credit to https://www.anandkanatt.com/how-do-i-detect-browser-window-closed-refreshed/#comment-15892. I simplified it a little by using the opener itself to check. Tested in Chrome Version 78.0.3887.7.

You may try this:

  • Add a refresh-close-detector.html file. Here's the sample code:
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Processing...</title>
</head>
<body>

<script>
  if (this.opener) {
    // the opener was refreshed, do something if you want
  } else {
    // the opener was closed, do something if you want
  }

  // you may want to close the pop up
  this.close()
</script>
</body>
</html>
  • In the page you want to identifying between refresh and close browser actions, add an event listener to unload:
window.addEventListener('unload', () => {
  open('refresh-close-detector.html', '', 'width=100,height=100');
})

Unfortunately there is no suggested or reliable way yet.

    $(window).bind('unload', function () {
        if (/Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
            console.log('firefox delete');
            var data = { async: false };
            endSession(data);
            return null;
        }
        else {
            console.log('NON-firefox delete');
            var data = { async: true };
            endSession(data);
            return null;
        }
    });

    function endSession(data) {
        var id = 0

        if (window) { // closeed
            id=1
        }

        $.ajax({
            url: '/api/commonAPI/'+id+'?Action=ForceEndSession',
            type: "get",
            data: {},
            async: data.async,
            success: function () {
                console.log('Forced End Session');
            }
        });
    }

Use if (window) to determines if closed or just reload. working for me.

Its a working solution

export class BootstrapComponent implements OnInit {

  validNavigation = 0;

  constructor(
    private auth: AuthenticationService
  ) { }

  ngOnInit() {
    const self = this;
    self.registerDOMEvents();
  }

  registerDOMEvents() {
    const self = this;
    window.addEventListener('unload', () => {
      if (self.validNavigation === 0) {
        self.endSession();
      }
    });
    document.addEventListener('keydown', (e) => {
      const key = e.which || e.keyCode;
      if (key === 116) {
        self.validNavigation = 1;
      }
    });
  }

  endSession() {
    const self = this;
    self.auth.clearStorage();
  }
}

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