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

标签 php javascript jquery codeigniter

我想在浏览器关闭或浏览器选项卡关闭时发出警报框。我有一些代码,但在这 1 条额外消息中即将到来。我想知道它来自警报框中的何处。如果您有任何其他代码,请发送给我或告诉我应该做什么..实际上我想避免第二个用户登录(为此,我创建 1 个 session ID 并保存在数据库中,之后每次用户登录时检查 session ID 是是否在数据库中,如果用户可以登录,当用户注销时, session ID 也会被删除,但浏览器或选项卡关闭,则 session ID 不会被删除。为此,我想检测之后我想将控件发送到 ajax Controller )这就是为什么我想知道 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 分钟或您认为适合您的任何时间,请更新条目并创建新 session 。

在这里查看类似的帖子 PHP /SESSION: Login one per user?

关于php - 如何检测浏览器/选项卡是否关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15739434/

相关文章:

php 添加具有特定 id 的列以及如何回显确切 id 的结果

php - 如何选择所有行的 HTML 表格

javascript - 向嵌套类添加新元素

javascript - JS将字符串中的每个#word替换为<div>#word</div>

javascript - 如何获取作为变量获取的 <tr> 内容的填充左值

php - 在 Laravel Eloquent 中使用 “with()” 函数连接列

javascript - 如何在 Wix 中使用 JavaScript 代码构建动态搜索表单?

javascript - for of 在JS中是如何实现的

javascript - 这两种 javascript 闭包语法之间的区别?

php - mysql sum 和 php 的简单计算怎么做?