3

我有一个问题,我有一个javascript功能要在浏览器关闭时使用,我该如何检测a browser is being closed

我已经对我得到的解决方案进行了一些研究,onunload或者beforeunload当我重新加载页面时这两个功能都在执行,是否有任何解决方案可以区分重新加载和浏览器/选项卡关闭。

4

3 回答 3

4

不,您不知道,HTML 页面不是浏览器的“所有者”,您只能有限地访问信息,并且此信息不在其中。

您可以知道用户何时离开您的页面,但您不知道为什么,因为这不关您的事......

于 2013-02-08T06:45:47.933 回答
2

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

于 2013-02-08T07:21:33.420 回答
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>
于 2013-08-16T15:27:42.253 回答