关闭选项卡时清除SESSION变量

3

当浏览器标签关闭时,我需要清除会话变量,但是目前我还没有找到任何解决方案。 我最接近的方法是使用JavaScript中的“onbeforeunload”函数。

<body onbeforeunload='destroySession()'>
    <!--Codes for the site includeing php scripts-->
</body>
<script type='text/javascript'>
    function destroySession(){
        $.ajax({
           url: "destroySession.php"
        });
     }
<script>

问题在于每次点击新链接、刷新页面,甚至提交表单时都会调用该函数。有没有更好的方法在关闭标签页时销毁会话变量?还是我做错了什么?请帮忙。

7
相信我,停止吧。你无法可靠且完全地完成这个任务。你可以以某些方式检测页面如何被导航离开(点击链接,提交表单等),但你将无法区分"关闭标签页"和"导航"及许多其他事件。很遗憾,我们不能做这种事情(因为像你所要求的清除会话将是不错的),但事情没有设置正确工作。请记住,这是一个网站,而不是桌面应用程序。 - Ian
可能是[关闭/终止浏览器或选项卡时关闭会话]的重复问题(https://dev59.com/VnI-5IYBdhLWcg3wTWdu)。 - Jamie Taylor
1
不要检测用户离开网站,正确的方法是在一段时间后将其超时。提示:实际上您不需要做任何事情来实现这一点!使用标签关闭会在某人同时在两个标签中打开您的应用程序(这并不罕见)然后决定关闭其中一个时变得麻烦。 - Kevin B
1
告诉我们你为什么要这样做,因为可能有你所不知道的标准实践。 - Flosculus
@Flosculus,我将一些用户的登录值存储在会话变量中。如果用户登录的选项卡被关闭并在同一浏览器中打开一个新选项卡,则这些值似乎仍然存在。这就是为什么我试图在选项卡关闭后销毁会话变量的原因。 - Bhuns
显示剩余3条评论
3个回答

4
没有一种安全的方法来处理您要查找的内容。onbeforeunload事件每次离开页面时执行。(昨天我在我的一个项目中遇到了类似的问题)。您能接近的是控制用户如何离开页面。请查看lan在一些评论中发布的链接。并检查Daniel Melo的回答。这是从这个问题的解决方案中可以得到的最接近的解决方案。我还发现了这个链接,但它基本上是从stackoverflow中给出的答案的提取。希望这可以帮助到您。

1

很遗憾,无法防止页面刷新(由表单提交或任何其他导航引起)触发“onbeforeunload”事件。


然而,您可以在某种程度上检测到是由于表单提交还是锚点点击引起的。 - Kevin B

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接