如何检测浏览器/选项卡是否关闭


How to detect Browser / Tab is closed

我想在浏览器关闭或浏览器选项卡关闭时发出警告框。我有一些代码,但在这1额外的消息即将到来。我想知道它从哪里来,在警报框里。如果你有其他代码,请发给我或告诉我该怎么做。实际上,我想避免第二个用户登录(为此,我创建1会话id并保存在DB之后,每次当用户登录时,它检查会话id是否在DB中,如果用户可以登录,当用户注销会话id也被删除,但浏览器或选项卡关闭,那么会话id未被删除。为此,我想检测一个之后,我想将控件发送到ajax控制器),这就是为什么我想知道从哪里来1个额外的消息。请解决我的问题…

<script type="text/javascript" >
var validNavigation = false;
function wireUpEvents() {
  var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation
  var leave_message = 'You sure you want to leave?'
  function goodbye(e) {
    if (!validNavigation) {
      if (dont_confirm_leave!==1) {
        if(!e) e = window.event;
        //e.cancelBubble is supported by IE - this will kill the bubbling process.
        e.cancelBubble = true;
        e.returnValue = leave_message;
        //e.stopPropagation works in Firefox.
        if (e.stopPropagation) {
          e.stopPropagation();
          e.preventDefault();
        }
        //return works for Chrome and Safari
        return leave_message;
      }
    }
  }
  window.onbeforeunload=goodbye;
  // 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>

你不能通过使用javascript代码来限制用户,如果用户在浏览器设置中禁用了javascript怎么办?

我认为你应该使用PHP和数据库(mysql)来处理它

当用户注册/登录时,在数据库的login_session表中插入一个新条目,包含时间和日期。在登录前检查条目是否存在,以及是否存在上次登录的时间。如果最后一次登录超过5分钟或任何你认为适合你的时间,更新条目并创建新的会话。

在这里查看类似的帖子PHP/SESSION:每个用户登录一个?