0

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.

Rohit416
  • 3,416
  • 3
  • 24
  • 41
  • Hi can you check this link might it will help https://stackoverflow.com/a/54801161/7924858 please up-vote – abhinavsinghvirsen Feb 21 '19 at 09:16
  • Thanks @abhinavxeon, Already tried, not working. – Ramakrishnan Ramar Feb 21 '19 at 09:19
  • There are many ways a browser window can be closed so a pure detection of the window getting close would be, unfortunately (sort of, fortunately) impossible. JavaScript has onundload and onbeforeunload events but they can-not cross the boundaries that the security restricitions has set for them. – Rohit416 Feb 21 '19 at 09:59

1 Answers1

1

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
  • Thanks @Cristian Traìna, I tried browser session storage, but session storage will clear once you close the browser. So I am not able to validate whether it's refresh or close on this. – Ramakrishnan Ramar Feb 21 '19 at 09:33