I'm looking for a solid solution to carry out an asynchronous event on a tab close in JavaScript
For context, I have a site with multiple (thousands) of pages that should only allow one user to edit a page at a time (i.e. two users can't be writing to the same page at once). So, when a user opens a page, I make a fetch
call to set a database flag for that page to mark it as locked.
Ideally, when the tab/window is closed or the page is left, I need to unset that locked flag; calling another async fetch
event to do so. I'm familiar with window.onunload
and window.onbeforeunload
and currently use those to try to call the fetch
to achieve this, but it seems this only works about half of the time. The other half of the time, the page will never unset the lock which causes major issues when other users need to access the page after
My code:
window.addEventListener('beforeunload', (ev) => {
ev.preventDefault();
if (condition) {
postToURL(`/url/to/unlock/page`); //postToURL is a custom function that essentially calls 'fetch'. Using the 'await' keyword seemed to have no effect here
}
return;
});
My question is, is there a more consistent way to do this? With a site that requires multiple users to constantly leave and open these pages, I need a more accurate way to handle this. Any help would be greatly appreciated, thanks!
The Beacon API was made for this scenario. It will send a request independent of the page closing.