Why browser refresh and close event detection is not working for IE and Safari

307 Views Asked by At

I need to call logout function on the close of browser window gets close. It's working fine in Chrome not working in IE and Safari.

I have tried the following code:

window.onbeforeunload = function (e) {
    // Your logic to prepare for 'Stay on this Page' goes here
    var evtobj = window.event ? event : e;
    if (evtobj == e) {
        //firefox
        if (!evtobj.clientY) {
           //server call
        }
    }
    else {
        //IE
        if (evtobj.clientY < 0) {
           //server call
        }
    }
    //return "Please click 'Stay on this Page' and we will give you candy";
};

I have tried a few other ways but they didn't work. Please advise.

1

There are 1 best solutions below

1
Christian Vincenzo Traina On

There is something wrong in your design, you SHOULDN'T rely on a client-side hook to perform logout. There are one billion of reasons why that event could not be executed. Just limit the onbeforeunload event to execute informational content and not critical actions.

By the way:

  • Don't return in your beforeunload event! This creates some issue in IE
  • Use window.sessionStorage to make some data last until the user closes the tab
  • Use session cookies to store your user's sensitive data like as tokens, and check if a user is logged on the server, and not on the client