javascript - onbeforeunload 根本不起作用

标签 javascript

我有这个代码:

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

我也有这个代码:

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

它们似乎都不起作用。我想做的就是在用户尝试离开页面时进行记录,但这并没有发生(最新的 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. See the HTML5 specification for more details. 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. In essence this means the user always confirms that the document may be unloaded.

Source

此外,在离开之前使用return语句提示用户

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

关于javascript - onbeforeunload 根本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37613401/

相关文章:

javascript - style.visibility 和 style.display 的区别

javascript - 谷歌地图 - 无法将文本和图像插入信息窗口

javascript - React.useEffect 在依赖项发生变化时不会触发

javascript - AngularJS指令: Substituting attribute values directly into template

javascript - window.innerWidth = 0?

javascript - 尝试使用 Spotify 的 API 创建播放列表时出现 "Request failed with status code 401"错误

javascript - postgreSQL 错误 : "constraint does not exist" (but it does exist. ..)

javascript - 我什么时候可以使用 $timeout(angular.noop)

javascript - 划分输入时的奇怪行为

javascript - Bitcore 多重签名 - 如何签署部分签名的多重签名比特币交易