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:
-
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()).
-
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.
-
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!