怎么用JS判断浏览器刷新还是关闭

JavaScript09

怎么用JS判断浏览器刷新还是关闭,第1张

页面加载时只执行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.screenLeftvar b = n >document.documentElement.scrollWidth-20if(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.screenLeftvar b = n >document.documentElement.scrollWidth-20if(b &&window.event.clientY <0 || window.event.altKey){alert("是关闭而非刷新")window.event.returnValue = ""//这里可以放置你想做的操作代码}else{alert("是刷新而非关闭")}}和function CloseOpen(event) {if(event.clientX<=0 &&event.clientY<0) {alert("关闭")}else{alert("刷新或离开")}}这些方法都不管用,但是我并没有放弃,想啊想啊........按照上面我得出结论,//对于ie,谷歌,360://页面加载时只执行onload//页面刷新时,刷新之前执行onbeforeunload事件,在新页面即将替换旧页面时onunload事件,最后onload事件。//页面关闭时,先onbeforeunload事件,再onunload事件。//对于火狐://页面刷新时,只执行onunload;页面关闭时,只执行onbeforeunload事件刷新的时候先onbeforeunload,然后取服务端请求数据,在新页面即将替换旧页面时onunload事件,而页面关闭时,先onbeforeunload事件,再立即onunload事件。那么在刷新的时候,onbeforeunload与onunload之间的时间肯定比关闭的时候时间长,经过测试确实如此。贴出我的测试代码:var _beforeUnload_time = 0, _gap_time = 0var is_fireFox = navigator.userAgent.indexOf("Firefox")>-1//是否是火狐浏览器window.onunload = function (){_gap_time = new Date().getTime() - _beforeUnload_timeif(_gap_time <= 5)$.post(pathName+"/back/bi!aaaa.s2?t="+_beforeUnload_time,{msg:"浏览器关闭",time:_gap_time},function(json){},"text")else$.post(pathName+"/back/bi!aaaa.s2?t="+_beforeUnload_time,{msg:"浏览器刷新",time:_gap_time},function(json){},"text")}window.onbeforeunload = function (){_beforeUnload_time = new Date().getTime()if(is_fireFox)//火狐关闭执行$.post(pathName+"/back/bi!aaaa.s2?t="+_beforeUnload_time,{msg:"火狐关闭"},function(json){},"text")}

标签只有onload\onunload\onbeforeunload事件,而没有onclose事件。不管页面是关闭还是刷新都会执行onunload事件。如何捕捉到页面关闭呢?

页面加载时只执行onload

页面关闭时只执行onunload

页面刷新时先执行onbeforeunload,然后onunload,最后onload。这样我们可以在onbeforeunload中加一个标记,在onunload中判断该标记,即可达到判断页面是否真的关闭了。

js判断页面是否关闭、刷新或跳转的方法:

window.onbeforeunload=function (){

alert("===onbeforeunload===")

if(event.clientX>document.body.clientWidth && event.clientY < 0 || event.altKey){

     alert("关闭了浏览器")

}else{

     alert("正在刷新页面")

}

}

这段代码就是判断触发onbeforeunload事件时,鼠标是否点击了关闭按钮,或者按了ALT+F4来关闭网页,如果是,则认为系统是关闭网页,否则在认为系统是刷新网页。