Chrome and beforeunload/unload

1.3k Views Asked by At

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?

1

There are 1 best solutions below

0
Branci On

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.