我需要捕获window.onbeforeunload事件

问题描述 投票:0回答:1

我正在一个需要捕获浏览器关闭事件(unloadbeforeunload)的项目中。为此,我尝试了下面的代码,但是它不起作用。

仅当我打开浏览器控制台窗口(也许只是一秒钟)时,该代码才起作用,但它是必需的,否则它将不起作用。

Example

$(window).on('beforeunload', function(e) {
  console.log('saved');
  return false;   
});
javascript jquery onbeforeunload onunload window.onunload
1个回答
0
投票

您必须防止发生卸载:

window.addEventListener('beforeunload', function (e) {
  // Cancel the event
  e.preventDefault();
  // Chrome requires returnValue to be set
  e.returnValue = '';
});

参考:https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

© www.soinside.com 2019 - 2024. All rights reserved.