6

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?

Alex
  • 4,674
  • 5
  • 38
  • 59
  • 1
    The snippet you posted works for me on Windows 10, Chrome 80.0.3987.87 incognito – blex Feb 13 '20 at 22:21
  • 1
    You shouldn't rely on onbeforeunload. https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload – Dan Feb 13 '20 at 22:24
  • I don't need it to be 100% reliable, but I'm curious why it doesn't work in incognito. Also I don't want to send a message to the user, just a beacon to the server. – Alex Feb 13 '20 at 22:27
  • All blocking actions most probably will be forbidden in incognito mode, so unload event may be triggered, but your function will not complete before window / navigator instance gets destroyed... a wild guess ... you can try to add an static iframe and try to trigger unload from it putting som JS code inside "srcDoc" attribute – Anonymous Feb 18 '20 at 21:03
  • Incognito is not the right way to test. In incognito, you still have your addons activated, which might interefere with the test. You should try on guest mode instead. – Jorjon Feb 24 '20 at 19:06

1 Answers1

0

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

Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43