I hope you are doing well!
I am trying to catch the window close or tab close or refresh event in my project and I tried all possible solutions but haven't succeeded.
I tried using:
useEffect(() => {
return () => {
window.alert("Alert");
};
});
and I tried:
useEffect(() => {
window.onbeforeunload = () => {
window.alert("alert");
};
return () => {
window.onbeforeunload = null;
};
});
which seems to only trigger if I have my window in the background for a while.
and I tried:
window.addEventListener("onbeforeunload", () => {
window.alert("alert");
});
but haven't been able to capture it.
I will use this functionality to send data to a specific API whenever the user closes the window or tab or refreshes (and possibly turns off the PC while on the page if that is event possible). But all these methods weren't working for me.
Is there any other way or is there a reason they aren't working?
Thank you for your time!