用js判断页面刷新或关闭的方法(onbeforeunload与onunload事件)html
Onunload,onbeforeunload都是在刷新或关闭时调用,能够在<script>脚本中经过window.onunload来指定或者在<body>里指定Onunload,onbeforeunload都是在刷新或关闭时调用,能够在<script>脚本中经过window.onunload来指定或者在<body>里指定。区别在于onbeforeunload在onunload以前执行,它还能够阻止onunload的执行。 Onbeforeunload也是在页面刷新或关闭时调用,Onbeforeunload是正要去服务器读取新的页面时调用,此时还没开始读取;而onunload则已经从服务器上读到了须要加载的新的页面,在即将替换掉当前页面时调用。Onunload是没法阻止页面的更新和关闭的。而 Onbeforeunload 能够作到。浏览器
页面加载时只执行onload 页面关闭时先执行onbeforeunload,最后onunload 页面刷新时先执行onbeforeunload,而后onunload,最后onload。服务器
一、onbeforeunload事件: 说明:目前三大主流浏览器中firefox和IE都支持onbeforeunload事件,opera还没有支持。 用法:测试
·object.onbeforeunload = handler ·<element onbeforeunload = “handler” … ></element>
描述: 事件触发的时候弹出一个有肯定和取消的对话框,肯定则离开页面,取消则继续待在本页。handler能够设一个返回值做为该对话框的显示文本。ui
触发于:url
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>onbeforeunload测试</title> <script> function checkLeave(){ event.returnValue="肯定离开当前页面吗?"; } </script> </head> <body onbeforeunload="checkLeave()"> </body> </html>
二、onunload事件 用法:firefox
·object.onbeforeunload = handler ·<element onbeforeunload = "handler"></element>
描述: 当用户关闭一个页面时触发 onunload 事件。code
触发于:orm
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>onunload测试</title> <script> function checkLeave(){ alert("欢迎下次再来!"); } </script> </head> <body onunload="checkLeave()"> </body> </html>
一个判断页面是否真的关闭和刷新的好方法:xml
window.onbeforeunload=function (){ alert("===onbeforeunload==="); if(event.clientX>document.body.clientWidth && event.clientY < 0 || event.altKey){ alert("你关闭了浏览器"); }else{ alert("你正在刷新页面"); } }
这段代码就是判断触发onbeforeunload事件时,鼠标是否点击了关闭按钮,或者按了ALT+F4来关闭网页,若是是,则认为系统是关闭网页,不然在认为系统是刷新网页。