W3School TIY Editor
W3School 在线教程
改变方向
暗黑模式
运行代码
<!DOCTYPE html> <html> <head> <script> function setCookie(cname,cvalue,exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires=" + d.toGMTString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } function refresh(){ window.location.reload(); } function helloworld() { var unloadCount = getCookie('unloadCount'); if( unloadCount == '' ){ unloadCount = 0; setCookie( 'unloadCount' , unloadCount ); document.getElementById("unloadCount").innerHTML = "你第一次访问该页面,尚未离开过。"; } else{ document.getElementById("unloadCount").innerHTML = "你已经离开页面<font color='red'> " + unloadCount + " </font>次了"; } } // 很多浏览器会阻止 onunload 事件中的弹窗,因此本示例采用 Cookie 记录unload的次数 function goodbye() { var unloadCount = getCookie('unloadCount'); if( unloadCount == '' ){ unloadCount = 0; } else{ unloadCount = parseInt(unloadCount); } unloadCount += 1; setCookie( 'unloadCount' , unloadCount ); } </script> </head> <body onunload="goodbye()" onload="helloworld()"> <h1>欢迎访问我的主页</h1> <p>很多浏览器会阻止 onunload 事件中的弹窗,因此本示例采用 Cookie 记录unload的次数</p> <p>关闭窗口或者按 F5 刷新页面,或者按 <input type="button" value="点击刷新页面" onclick="refresh()" /> 页面。</p> <div id="unloadCount"></div> </body> </html>