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