Home > Web Front-end > JS Tutorial > body text

How to Reliably Differentiate Between Page Refreshes and Browser Closures in Web Development?

Susan Sarandon
Release: 2024-11-04 22:22:01
Original
999 people have browsed it

How to Reliably Differentiate Between Page Refreshes and Browser Closures in Web Development?

Differentiating Browser Actions: Refresh vs. Close

In web development, distinguishing between page refreshes and browser closures during the ONUNLOAD event can pose a challenge. Here's a solution that leverages HTML5 local storage and client/server communication:

  1. On Page Unload:

    • Implement an onunload event handler on the window, such as myUnload().
    • Set a local storage flag myUnloadEventFlag to the current timestamp.
    • Notify the server that a disconnection (e.g., browser closure) may occur in a few seconds via an AJAX call (askServerToDisconnectUserInAFewSeconds()).
  2. On Page Load:

    • Implement an onload event handler on the body, such as myLoad().
    • Retrieve the myUnloadEventFlag from local storage and compare it to the current timestamp.
    • If the duration between the previous and current unload event is less than 10 seconds, it's likely a reload (cancel the disconnection request via askServerToCancelDisconnectionRequest()).
    • If the duration is greater than 10 seconds, it's probably a browser closure.
  3. Server-Side:

    • Collect disconnection requests in a list and set a timer thread (e.g., every 20 seconds) to inspect the list.
    • When a disconnection request times out (e.g., after 5 seconds), disconnect the user.
    • If a cancelation request is received, remove the corresponding disconnection request from the list.

This approach can also differentiate between tab/window closure, followed links, and submitted forms. It's applicable to browsers that support HTML5 local storage, and it's more reliable than relying on specific event properties like cursor position.

The above is the detailed content of How to Reliably Differentiate Between Page Refreshes and Browser Closures in Web Development?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!