在 Chrome Incognito 中不会触发 onbeforeunload 事件

Ale*_*lex 5 javascript google-chrome beacon sendbeacon

我一直在尝试发送信标 beforeunload,它似乎适用于几乎所有现代浏览器,除了处于隐身模式的 Chrome。

这是适用于所有现代浏览器的代码,除了处于隐身模式的 Chrome:

window.onbeforeunload = function() {
    navigator.sendBeacon("url");
}
Run Code Online (Sandbox Code Playgroud)

甚至这段代码似乎都不起作用:

window.onbeforeunload = function() { 
    console.log('before unload') 
}
Run Code Online (Sandbox Code Playgroud)

我做错了什么还是只是 Chrome 的错?

Mos*_*ini 0

您的设置是什么(SO,Chrome 版本)?

在 Chrome 80.0.3987.116 / Ubuntu 64 和 Chrome 79.0.3945.130 / Windows 10 上,以下代码片段工作正常:

window.addEventListener('beforeunload', (event) => {
  console.log("BEFORE")
  navigator.sendBeacon("http://www.google.it");
  // Cancel the event as stated by the standard.
  event.preventDefault();
  // Chrome requires returnValue to be set.
  event.returnValue = '';
});
Run Code Online (Sandbox Code Playgroud)

beforeunload 时发送的请求屏幕(隐身模式):

在此输入图像描述 此外,请注意:

为了阻止不需要的弹出窗口,某些浏览器不会显示在 beforeunload 事件处理程序中创建的提示,除非已与页面进行交互。此外,有些根本不显示它们。

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