0

I have a seemingly simple requirement but I have been stuck for days. Can someone give me a hand?

  • I need a confirmation prompt if the user tried to close the pop-up window
  • if the user click ok to close, I need to call an ajax call

My original design is to add an onbeforeunload event handler, have it returns a string which triggers a prompt. Works perfectly.

The problem is the next part. Added a unload listener, a pagehide listener, and a visibilitychange listener - in all three cases, Chrome doesn't fire the event if the user close the window, only if I refresh the window. Firefox works perfectly. I am using a sendbeacon call which should work in these scenarios and if I add a breakpoint to pause before the window closes, the beacon is sent, so it seems like Chrome is closing the document too fast and never bother sending the last beacon, which makes the whole exercise pointless.

Has anyone face similar issues and if so, any way to work around it?

Adrian Pang
  • 1,125
  • 6
  • 12
  • I think this will help you https://stackoverflow.com/questions/10311341/confirmation-before-closing-of-tab-browser –  Jun 22 '21 at 03:39
  • Thanks, but my problem is not with the prompt (which is working) but the unload event - I can't do the ajax in beforeunload since I need the prompt but unload seems to be too late for this. – Adrian Pang Jun 22 '21 at 03:49
  • pagehide, unload and beforeunload aren't reliable https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event#usage_notes you can use them for some optimisations / cleanup, but you can't rely on them for anything critical. visibilitychange is the only one whose specs make it reliable, but i don't know if you can't interrupt it to prompt the user, and i don't know about safari support. – Sheraff Jun 22 '21 at 04:58

1 Answers1

1

I'm struggling with the same problem.

Reading about the event on the documentation I've noticed that it is an unstable event, and moreover in the compatibility table, Chrome is set to "not supported".

But I noticed that chrome fire the event one time only. If I close the browser and then i re-open it, the first time the event is fired, but it not work with tab closing.

Branci
  • 31
  • 3