當由頁面刷新或瀏覽器關閉觸發時,ONUNLOAD 事件在區分這兩個操作時提出了挑戰.
為了解決此問題,以下解決方案利用HTML5 本地儲存和客戶端/伺服器AJAX 通訊:
<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>
以上是如何區分onUnload事件中頁面刷新和瀏覽器關閉?的詳細內容。更多資訊請關注PHP中文網其他相關文章!