如何使用javascript检测浏览器选项卡刷新或关闭

时间:2013-02-08 06:43:57

标签: javascript jquery html

我有一个问题,我有一个javascript函数,我想在浏览器关闭时使用它,如何检测a browser is being closed

我已经做了一些研究,我得到了像onunloadbeforeunload这样的解决方案,但是当我重新加载页面时,这两个函数都被执行了,有没有我可以区分重载和浏览器的解决方案/ tab close。

3 个答案:

答案 0 :(得分:4)

不,你不可能知道,HTML页面不是浏览器的“所有者”,你只能有限地访问信息,而且这些信息不在其中。

您可以知道用户何时离开您的网页,但您无法知道原因,因为这不属于您的业务......

答案 1 :(得分:2)

gdoron是正确的,因为您无法确定用户“离开页面”的原因/方式。 在极端情况下,如果点击了浏览器的CLOSE按钮,您可以确定mousedown事件,并触发警报。 但这可能需要跟踪mousedown事件的X和Y,这不是一个非常好的做事方式。而且我认为您无法准确确定标签是否已关闭。

答案 2 :(得分:1)

回答是,

</head>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" language="javascript">

var validNavigation = false;

function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("bye");
}

function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
  if (!validNavigation) {
     endSession();
  }
 }

// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
  validNavigation = true;
}
});

// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});

 // Attach the event submit for all forms in the page
 $("form").bind("submit", function() {
 validNavigation = true;
 });

 // Attach the event click for all inputs in the page
 $("input[type=submit]").bind("click", function() {
 validNavigation = true;
 });

}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();  
}); 
</script>    
</head>
<body>
<h1>Eureka!</h1>
  <a href="http://www.google.com">Google</a>
  <a href="http://www.yahoo.com">Yahoo</a>
</body>
</html>
相关问题