js判断页面是关闭还是刷新

JavaScript014

js判断页面是关闭还是刷新,第1张

<mce:script type="text/JavaScript"><!--function close(evt) //author: sunlei{var isIE=document.all?true:falseevt = evt ? evt :(window.event ? window.event : null)if(isIE){//IE浏览器var n = evt.screenX - window.screenLeftvar b = n >document.documentElement.scrollWidth-20if(b &&evt.clientY<0 || evt.altKey){//alert("是关闭而非刷新")window.location.href="../include/logout.PHP"}else{//alert("是刷新而非关闭")return false}}else{//火狐浏览器if(document.documentElement.scrollWidth!=0){//alert("是刷新而非关闭")//window.location.href="report_list.php?ss=1"return false}else{alert("是关闭而非刷新")//window.location.href="repost_list.php?ss=0"//alert("bbbbbbb")}}}// --></mce:script><BODY onunload="close(event)">

页面加载时只执行onload 

页面关闭时只执行onunload 

页面刷新时先执行onbeforeunload,然后onunload,最后onload。

经过验证我得出的结论是:

//对于ie,谷歌,360:

//页面加载时只执行onload

//页面刷新时,刷新之前执行onbeforeunload事件,在新页面即将替换旧页面时onunload事件,最后onload事件。

//页面关闭时,先onbeforeunload事件,再onunload事件。

//对于火狐:

//页面刷新时,只执行onunload;页面关闭时,只执行onbeforeunload事件

那么回归正题,到底怎样判断浏览器是关闭还是刷新?我按照网上的各种说法实验千百遍,都未成功,其中各种说法如下:

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 = "" //这里可以放置你想做的操作代码 

}else

alert("是刷新而非关闭") 

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 = "" //这里可以放置你想做的操作代码 

}else

alert("是刷新而非关闭") 

}