Home  >  Article  >  Web Front-end  >  How to Distinguish Between Page Refresh and Browser Closure in JavaScript?

How to Distinguish Between Page Refresh and Browser Closure in JavaScript?

DDD
DDDOriginal
2024-11-03 17:42:29336browse

How to Distinguish Between Page Refresh and Browser Closure in JavaScript?

Identifying Page Refresh vs. Browser Closure

When triggering the ONUNLOAD event, it becomes difficult to distinguish between refreshing a page and closing the browser. This article presents a solution to this problem.

Solution

This solution utilizes HTML5's local storage and server-client AJAX communication:

  1. Window Unload Handler:

    • Register an onunload handler on the window.
    • In this handler, set a local storage flag to indicate page unloading (myUnloadEventFlag).
    • Send an AJAX request to the server, asking to disconnect the user after a specified delay (e.g., 5 seconds)
  2. Body Load Handler:

    • Register an onload handler on the page body.
    • In this handler, check the local storage flag for the unload event.
    • If the difference between the current time and the flag's time is less than the specified delay, the page has been reloaded and the server's disconnection request must be canceled.
    • Otherwise, it is a browser closure.
  3. Server Handling:

    • Maintain a list of disconnection requests.
    • Run a timer that regularly inspects the list.
    • When a request's timeout expires, disconnect the user.
    • If a cancellation request is received, remove the corresponding disconnection request from the list.

This approach distinguishes between tab/window closures and page reloads by considering the timing of unload events. It is applicable to other events like followed links and submitted forms by placing event handlers on relevant pages.

Limitations:

This solution requires HTML5 local storage support and may not work on older browsers like MSIE7.

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

Statement:
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