如何检测浏览器选项卡刷新或使用JavaScript关闭 [英] How can I detect browser tab refresh or close using javascript

查看:91
本文介绍了如何检测浏览器选项卡刷新或使用JavaScript关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,当浏览器关闭时,我有一个 javascript 函数,我该如何检测浏览器正在关闭

I have one problem, I have a javascript function which I want to use when the browser is closed, How can I detect that a browser is being closed?

我做了一些研究,得到了像 onunload beforeunload 但是当我重新加载页面时,这两个函数都正在执行,是否有任何解决方案可以区分重新加载和浏览器/选项卡关闭。

I have made some research on that I got solution like onunload or beforeunload but both the functions are being executed when I am reloading the page, Is there any solution that I can differentiate reload and browser/tab close.

推荐答案

答案是,

</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>

这篇关于如何检测浏览器选项卡刷新或使用JavaScript关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆