Identifying Between Refresh And Close Browser Actions

前端 未结 13 1209
孤街浪徒
孤街浪徒 2020-11-22 15:29

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

相关标签:
13条回答
  • 2020-11-22 15:44

    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)
        }
    });
    
    0 讨论(0)
  • 2020-11-22 15:47

    I just tried this and it solved the issue: Create a sessionStorage object which will get destroyed when the user closes the browser. We can check the sessionStorage object to find if the user has closed the browser or refreshed the page(sessionStorage object will not be destroyed on page refresh).

    0 讨论(0)
  • 2020-11-22 15:48

    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.

    0 讨论(0)
  • 2020-11-22 15:50

    Today I had the same problem and found a possible solution that I want to share with you.

    While thinking about what could help to discern between refresh and close, cookies came to my mind. I remember that setting a cookie without an explicit expiration date, renders it available only for the current session. And a current session is clearly valid until the browser is closed. This does not include closing a tab, but my problem was about user authentication and I didn't want to logout the user only for having closed a tab (I think that's the same approach as the ASPXAUTH cookie of ASP.NET).

    So, I put a simple cookie in the document.cookies collection when user logged in and checked it on page load: if cookie was still there it was a refresh or a reopened tab and user data was kept, if cookie was not present session had expired so user data was cleared (same as an explicit logout).

    Hope this approach can be useful to someone else!

    0 讨论(0)
  • 2020-11-22 15:51

    Unfortunately there is no suggested or reliable way yet.

    0 讨论(0)
  • 2020-11-22 15:52

    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');
    })
    
    0 讨论(0)
提交回复
热议问题