
Hello Arpita Bhattacharya,
Thank you for your question regarding API calls when closing the Microsoft Edge browser using the beforeunload
event.
The issue you’re experiencing is due to browser limitations:
- When the
beforeunload
event occurs (such as when a user closes a tab or browser), the browser quickly terminates all JavaScript running on the page. - Asynchronous API calls, such as those made with
fetch
,XMLHttpRequest
, orasync/await
, often do not have enough time to execute or may be cancelled if the browser closes too quickly. - This is a general restriction in modern browsers, not just Microsoft Edge.
The best solution currently available:
- You should use the
navigator.sendBeacon()
API. This method is specifically designed for sending small amounts of data to the server when the page is about to be closed. While it’s not 100% guaranteed,sendBeacon
has the highest success rate for sending data when the page is unloading. - Here’s a sample implementation:
window.addEventListener('beforeunload', function (event) {
const url = 'https://your-api-endpoint.com/unlock';
const data = { message: "Tab is being closed" };
const blob = new Blob([JSON.stringify(data)], {type : 'application/json'});
navigator.sendBeacon(url, blob);
event.returnValue = '';
});
Notes:
- Only small amounts of data should be sent, and you won’t receive a response from the server.
- If the user closes the browser very quickly or shuts down the computer abruptly, there is still a chance that the data might not be sent.
You can also find a detailed walkthrough in our documentation here:
MDN Web Docs - navigator.sendBeacon() WHATWG HTML Spec
In summary:
You cannot rely on asynchronous API calls during browser/tab close events; only sendBeacon
should be used for this purpose. This is a browser limitation, not a bug in your code.
If you need help implementing sendBeacon
or would like to test it, I’m happy to assist!
I hope this helps you get things back on track quickly! If you agree with our suggestion, feel free to interact with the system accordingly!