用js判断页面刷新或关闭的方法
<title>onbeforeunload测试</title>
<script>
function checkLeave(){
???? event.returnValue="确定离开当前页面吗?";
}
</script>
</head>
<bodyonbeforeunload="checkLeave()">
</body>
</html>
2、onunload事件
用法:
object.onbeforeunload = handler
<element onbeforeunload ="handler"></element>
描述:
当用户关闭一个页面时触发 onunload 事件。
触发于:
关闭浏览器窗口
通过地址栏或收藏夹前往其他页面的时候
点击返回,前进,刷新,主页其中一个的时候
点击 一个前往其他页面的url连接的时候
调用以下任意一个事件的时候:click,document write,document open,documentclose,window close ,window navigate ,windowNavigateAndFind,location replace,location reload,form submit.
当用window open打开一个页面,并把本页的window的名字传给要打开的页面的时候。
重新赋予location.href的值的时候。
通过input type=”submit”按钮提交一个具有指定action的表单的时候。
示例:
<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>
<bodyonunload="checkLeave()">
</body>
</html>
一个判断页面是否真的关闭和刷新的好方法(最好用)
window.onbeforeunload=function (){
alert("===onbeforeunload===");
if(event.clientX>document.body.clientWidth&& event.clientY < 0|| event.altKey){
????alert("你关闭了浏览器");
}else{
????alert("你正在刷新页面");
}
}
这段代码就是判断触发onbeforeunload事件时,鼠标是否点击了关闭按钮,或者按了ALT+F4来关闭网页,如果是,则认为系统是关闭网页,否则在认为系统是刷新网页。