简体   繁体   English

onbeforeunload根本不起作用

[英]onbeforeunload not working at all

I have this code: 我有以下代码:

(function() {
      window.onbeforeunload = function () {
          alert("hi")
          console.log("unloading");
      };
})();

I also have this code: 我也有这段代码:

window.addEventListener("beforeunload", function() {
   alert("hi")
   console.log("unloading")
});

None of them seem to work. 他们似乎都不起作用。 All I want to do is log when the user tries to leave the page, but this isn't happening (latest Chrome, latest Firefox, Edge....), can anybody shed some light on why it's not working? 我只想在用户尝试离开该页面时进行日志记录,但是这种情况没有发生(最新的Chrome,最新的Firefox,Edge ....),有人可以阐明为什么它不起作用吗?

Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. 从2011年5月25日开始,HTML5规范规定在此事件期间可以忽略对window.alert(),window.confirm()和window.prompt()方法的调用。 See the HTML5 specification for more details. 有关更多详细信息,请参见HTML5规范。 Note also that various mobile browsers ignore the result of the event (that is, they do not ask the user for confirmation). 还要注意,各种移动浏览器都忽略事件的结果(即,它们不要求用户确认)。 Firefox has a hidden preference in about:config to do the same. Firefox在about:config中具有隐藏的首选项以执行相同的操作。 In essence this means the user always confirms that the document may be unloaded. 从本质上讲,这意味着用户始终会确认文档可能已卸下。

Source 资源

Also, use return statement to prompt user before leaving 另外,使用return语句在离开前提示用户

window.addEventListener("beforeunload", function() {
   return "hi";
});

Do it this way: 这样做:

  window.onbeforeunload = function (e) {
          console.log("unloading");
          return "Hi";
      };

That will alert Hi when page unloads and also prints unloading in console 这将在页面卸载时向Hi发出警报,并在控制台中显示打印unloading

 function myFunction() { return "Write something clever here..."; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body onbeforeunload="return myFunction()"> </body> 

You have to return from the onbeforeunload: 您必须从onbeforeunload返回:

(function() {
  window.onbeforeunload = function () {
      alert("hi")
      console.log("unloading");
      return null;
      };
    })();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM