Chrome Incognito不会触发onbeforeunload事件 [英] Event onbeforeunload isn't fired in Chrome Incognito
问题描述
我一直在尝试在 beforeunload
上发送信标,它似乎可以在除隐身模式下的Chrome之外的几乎所有现代浏览器上使用.
I've been trying to send a beacon on beforeunload
and it seems to work on pretty much all modern browsers, except Chrome in incognito mode.
这是可在所有现代浏览器中使用的代码,但隐身模式下的Chrome除外:
This is the code that works in all modern browsers, except Chrome in incognito mode:
window.onbeforeunload = function() {
navigator.sendBeacon("url");
}
甚至这段代码似乎也不起作用:
Not even this code doesn't seem to work:
window.onbeforeunload = function() {
console.log('before unload')
}
我在做错什么还是仅仅是Chrome的错?
Am I doing anything wrong or is it just Chrome's fault?
推荐答案
您的设置是什么(SO,Chrome版本)?
What's your setup (SO, Chrome version) ?
在Chrome 80.0.3987.116/Ubuntu 64和Chrome 79.0.3945.130/Windows 10上,以下代码片段非常有用:
On Chrome 80.0.3987.116 / Ubuntu 64 and Chrome 79.0.3945.130 / Windows 10 the below snippet works falwlessy:
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 = '';
});
在卸载之前发送的请求(隐身模式)的屏幕:
Screen of the request (incognito mode) sent on beforeunload:
此外,请注意:
为防止不必要的弹出窗口,某些浏览器不显示提示除非页面已被创建,否则在beforeunload事件处理程序中创建与之互动.而且,有些根本不显示它们.
To combat unwanted pop-ups, some browsers don't display prompts created in beforeunload event handlers unless the page has been interacted with. Moreover, some don't display them at all.
参考: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
这篇关于Chrome Incognito不会触发onbeforeunload事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!