onunload ,onbeforeunload都是在刷新或关闭时调用,可以在<script>脚本中通过window.onunload来指定或者在<body>里指定。区别在于onbeforeunload在onunload之前执行,它还可以阻止onunload的执行。
onbeforeunload也是在页面刷新或关闭时调用,onbeforeunload是正要去服务器读取新的页面时调用。此时还没有还没有读取;而onunload则已经从服务器上读到了需要加载的新的页面,在即将替换当前页面时调用。onunload是无法阻止页面的更新和关闭的。而onbeforeunload可以做到。曾经做了一个考试系统,涉及到防止用户半途退出考试(有意或者无意)
<scripttype="text/javascript">
window.onbeforeunload = onbeforeunload_handler;
functiononbeforeunload_handler(){
var waring ="确定关闭浏览器?";
returnwaring;
}
window.onunload = onunload_handler;
functiononunload_handler(){
var waring ="谢谢光临";
alert(waring);
}
</script>
window.onbeforeunload = function() //author:meizz
{
var n = window.event.screenX -window.screenLeft;
var b = n >document.documentElement.scrollWidth-20;
if(b && window.event.clientY< 0 ||window.event.altKey)
{
alert("是关闭而非刷新");
window.event.returnValue = "";//这里可以放置你想做的操作代码
}
}
http://wuhaidong.iteye.com/blog/811816
方案一:
Html代码- <html>
- <head>
- <script language="javascript">
- window.onbeforeunload= function() //author:meizz
- {
- var n= window.event.screenX -window.screenLeft;
- var b= n >document.documentElement.scrollWidth-20;
- if(b &&window.event.clientY < 0|| window.event.altKey)
- {
- alert("关闭浏览器!");
- window.event.returnvalue= "";//这里可以放置你想做的操作代码
- }
- }
- </script>
- </head>
- </html>
<html> <head> <script language="javascript"> window.onbeforeunload = function() //author: meizz { var n = window.event.screenX - window.screenLeft; var b = n > document.documentElement.scrollWidth-20; if(b && window.event.clientY < 0 || window.event.altKey) { alert("关闭浏览器!"); window.event.returnvalue = ""; //这里可以放置你想做的操作代码 } } </script> </head> </html>
方案二:
Js代码- <html>
- <head>
- <title>判断是刷新还是关闭</title>
- </head>
- <script>
- function CloseOpen(event){
- if(event.clientX<=0&& event.clientY<0){
- alert("关闭");
- }
- else
- {
- alert("刷新或离开");
- }
- }
- </script>
- <body onunload="CloseOpen(event)">
- </body>
- </html>
页面加载时只执行onload
页面关闭时只执行onunload
不管页面是关闭还是刷新都会执行onunload事件。
页面刷新时先执行onbeforeunload,然后onunload,最后onload。
<html> <head> <title>判断是刷新还是关闭</title> </head> <script> function CloseOpen(event) { if(event.clientX<=0 && event.clientY<0) { alert("关闭"); } else { alert("刷新或离开"); } } </script> <body onunload="CloseOpen(event)"> </body> </html>