asp.net 或JS怎么判断 页面是否打开

JavaScript017

asp.net 或JS怎么判断 页面是否打开,第1张

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

window.onbeforeunload=function (){

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

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

alert("关闭了浏览器")

}else{

alert("正在刷新页面")

}

}

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

可以利用Cookies来判断,先查找Cookies中某个指定的值,未找到说明是首次打开,然后再把这个值写入Cookies,这样下次再打开这个页面时js就知道不是首次打开了。比如:

if(document.cookie.indexOf("a=hello")==-1){

    alert("首次打开!")

    var t=new Date(new Date().getTime()+1000*60*60*24*30)

    document.cookie="a=hello expires="+t.toGMTString()

}else{

    alert("再次打开!")

}

//这个Cookies的有效期为30天(到期后会重新判断为首次打开),你可以自己修改