Chrome Incognito不会触发onb​​eforeunload事件

时间:2020-02-13 22:19:51

标签: javascript google-chrome beacon sendbeacon

我一直在尝试在beforeunload上发送信标,它似乎可以在几乎所有现代浏览器上运行,但隐身模式下的Chrome除外。

这是可在所有现代浏览器中使用的代码,但隐身模式下的Chrome除外:

window.onbeforeunload = function() {
    navigator.sendBeacon("url");
}

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

window.onbeforeunload = function() { 
    console.log('before unload') 
}

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

1 个答案:

答案 0 :(得分: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 = '';
});

在卸载之前发送的请求(隐身模式)的屏幕:

enter image description here 此外,请注意:

为防止不必要的弹出窗口,某些浏览器不显示提示 除非页面已经被创建,否则在beforeunload事件处理程序中创建 与之互动。而且,有些根本不显示它们。

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