Event onbeforeunload isn't fired in Chrome Incognito

冷暖自知 提交于 2021-02-08 15:12:37

问题


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.

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') 
}

Am I doing anything wrong or is it just Chrome's fault?


回答1:


What's your setup (SO, Chrome version) ?

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:

Furthermore, notice:

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.

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



来源:https://stackoverflow.com/questions/60217338/event-onbeforeunload-isnt-fired-in-chrome-incognito

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!