Window.onbeforeunload

Hi,

When a user launches the AP activity in a tab or window, there is a chance that they may close it accidentally. I want to make an API call in JS to a server to close some resources if this happens. I found window.onbeforeunload online. I want to know if there is something similar. I tried on unload, but it does not call the script. I think that triggers only when transitioning from one slide to another.

Regards
Ali

Hi Ali,

It’s very tricky, even for a JavaScript developer.
Firstly, window beforeunload and unload events are not fired in some cases, especially on a mobile device.
Secondly, during page dismissal, synchronous ajax request is not allowed in some browsers, and async request is not reliable.

So I think you should use sendBeacon or Fetch API keepalive to send data to your server in this case.
And you can consider using a more reliable event is visibilitychange event, but it doesn’t mean a page unload.

Regards

Thanks Toan. I will look further into these options.
Will post any updates I find here to help the community.