Event onbeforeunload isn't fired in Chrome Incognito

4.7k Views Asked by At

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

There are 1 best solutions below

7
On

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:

enter image description here 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