Home > Web Front-end > JS Tutorial > How to Distinguish Between Page Refresh and Browser Close in the onUnload Event?

How to Distinguish Between Page Refresh and Browser Close in the onUnload Event?

Patricia Arquette
Release: 2024-11-04 03:51:29
Original
445 people have browsed it

How to Distinguish Between Page Refresh and Browser Close in the onUnload Event?

Distinguishing Between Page Refresh and Browser Close Actions

When triggered by either a page refresh or a browser close, the ONUNLOAD event presents a challenge in differentiating between the two actions.

To address this issue, the following solution utilizes HTML5 local storage and client/server AJAX communication:

Solution Implementation

Page onLoad Event Handler

<code class="javascript">function myLoad(event) {
    if (window.localStorage) {
        var t0 = Number(window.localStorage['myUnloadEventFlag']);
        if (isNaN(t0)) t0=0;
        var t1=new Date().getTime();
        var duration=t1-t0;
        if (duration<10*1000) {
            // It's a browser reload
        } else {
            // It's a browser close
        }
    }
}</code>
Copy after login

Page onUnload Event Handler

<code class="javascript">function myUnload(event) {
    if (window.localStorage) {
        // Flag the page as unloading
        window.localStorage['myUnloadEventFlag']=new Date().getTime();
    }

    // Notify the server to disconnect the user in a few seconds
    askServerToDisconnectUserInAFewSeconds();
}</code>
Copy after login

Server Implementation

  • Collect disconnection requests in a list.
  • Set a timer thread to inspect the list regularly and disconnect users after a timeout (5 seconds).
  • Remove disconnection requests from the list upon receiving cancellation requests from the client.

Key Points

  • By using the unload event instead of beforeUnload, attachments can be handled properly.
  • This solution is limited to browsers that support HTML5 local storage.
  • Alternative approaches based on event.clientY or X position are less reliable.

The above is the detailed content of How to Distinguish Between Page Refresh and Browser Close in the onUnload Event?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template