Javascript 如何识别用户是否重新加载网页?

Javascript 如何识别用户是否重新加载网页?,javascript,jquery,Javascript,Jquery,我的实际任务是在用户关闭选项卡或窗口时确认用户。 为此,我编写了以下代码 var validNavigation = false; function wireUpEvents() { var dont_confirm_leave = 0; var leave_message = 'You sure you want to leave?' function goodbye(e) { if (!validNavigation) { if (dont_con

我的实际任务是在用户关闭选项卡或窗口时确认用户。 为此,我编写了以下代码

 var validNavigation = false;

 function wireUpEvents() {

  var dont_confirm_leave = 0; 
   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;
  });

  // Attach the event click for all inputs in the page
  $("input[type='button']").bind("click", function() {
    validNavigation = true;
  });

}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
  wireUpEvents();
});
这里的问题是,如果用户重新加载网页,它会询问确认。 所以我需要绑定重载事件

请帮帮我。。。 提前感谢

使用或
.on('unload',handler)

使用或
.on('unload',handler)


如果页面重新加载是在文档内部的用户交互之后完成的,则可以使用任何类型的标志/逻辑。如果您想在用户按F5时处理所有情况,据我所知,JavaScript无法知道用户导航到哪里,即是否“仅仅”重新加载。顺便说一句:除了F5,Mac上的Safari还使用了其他按键进行重新加载/导航⌘+R当然,您可以通过上下文菜单或应用程序菜单、脚本、刷新标题、浏览器加载项等来完成。抓到
F5
会让你一事无成。对于JavaScript,页面重新加载看起来就像任何其他导航一样-对话框必须弹出。另一方面,如果用户导航离开,对其进行窃听是不礼貌的。简单的解决方案:除非有未保存的更改,否则不要这样做。Tomalak:我的任务是在用户关闭web应用程序时将其登录状态更新为false。因此,当用户重新加载页面时,使用我的代码,然后状态更新为false。只有当用户关闭窗口时,我才需要设置false。如果页面重新加载是在用户在文档中交互之后完成的,则可以使用任何类型的标志/逻辑。如果您想在用户按F5时处理所有情况,据我所知,JavaScript无法知道用户导航到哪里,即是否“仅仅”重新加载。顺便说一句:除了F5,Mac上的Safari还使用了其他按键进行重新加载/导航⌘+R当然,您可以通过上下文菜单或应用程序菜单、脚本、刷新标题、浏览器加载项等来完成。抓到
F5
会让你一事无成。对于JavaScript,页面重新加载看起来就像任何其他导航一样-对话框必须弹出。另一方面,如果用户导航离开,对其进行窃听是不礼貌的。简单的解决方案:除非有未保存的更改,否则不要这样做。Tomalak:我的任务是在用户关闭web应用程序时将其登录状态更新为false。因此,当用户重新加载页面时,使用我的代码,然后状态更新为false。我只需要在用户关闭窗口时设置false。
$(window).unload(function() {
  // your code here
});