I'm trying to run some JS code when a user closes my page. I found this on the internet:
window.addEventListener('beforeunload', (event) => {
event.returnValue = null
console.log("unload")
});
When I try to close my page with this code in my document, Chrome gives me a dialog and asks "Leave site? Changes that you made may not be saved", with the options "Leave" and "Cancel". It also runs the console.log
, so it seems to work fine right? However, the console.log
runs at the same time that the prompt appears. So I don't know that the user actually closed the site, because they could have clicked cancel for all I know. And I only want to run my code if I know for a fact that the user actually closed the page.
I would really prefer to avoid using WebSockets, or doing some sort of continuous polling to check if the user is still on the page, if possible. However, if there is really no other way to do it, I might resort to one of these methods, but I am really hoping there is another way to do it.
Any ideas?
EDIT: I don't actually care about what triggers the beforeunload
event. Like, the user might click the close button in their browser, they might refresh the page, they might click a link, or they might type another url into their browser. I don't care. I just don't want to run my code if they click cancel on the prompt that appears, because then they aren't actually going to unload the page after all. Also, I'm not doing anything intrusive, just some database stuff behind the scenes, so it's fine if the code somehow runs after the page has been closed (I think I remember some stuff about sendBeacon
or something being able to do it, but I'm not sure), or it's also fine if no prompt appears at all, and it just runs my code and then closes the page.