当由页面刷新或浏览器关闭触发时,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中文网其他相关文章!