您的位置:首页 > Web前端 > JavaScript

js 判断窗口刷新和关闭,分各种情况

2014-05-08 16:46 176 查看
项目要求记录页面的刷新和关闭 次数,在网上查了各种资料,都是用窗口大小的原理来识别,但其实当调用onbeforeunload事件的时候是不会捕捉鼠标的mousemove事件的,获取不到event.clientX事件,而且鼠标一旦离开页面范围,就不能继续获取鼠标的e.clientX位置了,所以我采用了下面的方法,测试可用的:

原理是刷新只记录F5和右键两种方式,其他认为是关闭,关闭只识别alt+f4以及Mac机子的Commad+q其他认为是点击标签或窗口关闭。

刷新调用:onbeforeunload,onunload,onload;

关闭调用:onbeforeunload,onunload;

方法如下:

var currentKeyCode = -1,altkey=false ,rightKey= false,pageY=0,listernType= null;

$(window).keydown( function(){

top.altkey = event.altKey;

top.currentKeyCode = event.keyCode;

});

$(document).on("contextmenu" , function(e){

rightKey = true ;

});

function isReloadOrClose(event){

var msg= null ;

if (currentKeyCode
== 116 || rightKey) {

//116:F5

if (currentKeyCode
== 116){

msg = "刷新窗口!(F5)" ;

}

if (rightKey){

msg = "右键刷新窗口!" ;

}

top.listernType = "reload" ;

} else{

msg = "点击关闭窗口" ;

top.listernType = "close" ;

if ((altkey
|| currentKeyCode == 18) || (currentKeyCode == 115) ){

msg = "关闭窗口!(alt+F4)" ;

}

if (currentKeyCode
== 91){

msg = "Mac关闭窗口!(commad)" ;

}

}

currentKeyCode = -1,altkey=false ,rightKey= false,pageY=0,listernType= null;

return msg;

}

window.onbeforeunload = function (event)
{

return isReloadOrClose(event)

}

$(window).unload( function(event){

alert( "Bye now!" );

});

网上还有一种识别刷新的方法,没试过,方法如下:

原文是http://www.tedpavlic.com/post_detect_refresh_with_javascript.php

原文给了两个方法,方法一大致翻译如下,

对于大多数浏览器,表单隐藏域的值在浏览器刷新后仍被保留。所以可以给页面添加一个拥有默认值(本例中为空)的表单隐藏域,如果在pageload事件中此默认值未改变,则说明pageload事件不是被刷新触发的,此时可以给这个表单隐藏域设置一个非默认值;若在pageload事件中此表单隐藏域的值被改变了(在非刷新页面导致的pageload事件中改变的),那么说明此时的pageload事件是被刷新触发的。

代码如下,

<html>

<head>

<script language="JavaScript"> <!--

function checkRefresh()

{

if( document.refreshForm.visited.value == "" )

{

// 非刷新,改变默认值

document.refreshForm.visited.value = "1";

// 非刷新情况下的其它应用逻辑

}

else

{

// 刷新页面导致下面代码的执行

// 刷新情况下的其它应用逻辑

}

} -->

</script>

</head>

<body onLoad="JavaScript:checkRefresh();">

<form name="refreshForm">

<input type="hidden" name="visited" value="" />

</form>

</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: