So for some reason, if I wanted to run a function to update a database when the user leaves a page, I can do that with a useEffect return/cleanup function. But is there a way to do that if they close the page/browser?
useEffect(() => {
return () => {
window.open("https://www.google.com", "_blank");
};
}, []);
I tried testing like so, but never seemed to work. So I am wondering if there is a way to do this.
CodePudding user response:
To get notified when the window is just about to close, use the onbeforeunload event:
useEffect(() => {
const onBeforeUnload = (e) => {
// run your cleanup code here
}
window.addEventListener('beforeunload', onBeforeUnload);
return () => {
window.removeEventListener('beforeunload', onBeforeUnload);
}
}, []);
You are limited in terms of what you can do during this event. If you want, you can prompt the user whether they really want to close the page, which you do like this:
const onBeforeUnload = (e) => {
// Cancel the event
e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
// Chrome requires returnValue to be set
e.returnValue = '';
}
This will display an alert-like message, which you cannot customize. Typically you should only do this if the user has done something where they would expect this kind of message. Ie, they've made changes, and those changes havn't been saved, and they'll be annoyed if they lose them. If you're just running cleanup code, you probably don't need to do this.
You cannot redirect them to another page or show a custom alert. Malicious pages would love this: "Ha ha, you tried to leave my page, well i'm routing you back to it instead".