Reputation: 91
I'm trying to refresh react website and I want to show an alert and if user check confirm the website is going to home page with route whenever refresh my website.
so, I tried to use onbeforeunload
but it's not what i expected .
This is what im using, but when i refresh then it can't go to home page
useEffect(() => {
window.onbeforeunload = function () {
return true;
};
return () => {
window.onbeforeunload = null;
};
}, []);
Upvotes: 1
Views: 197
Reputation: 12787
You should using addEventListener
and removeEventListener
to do this:
useEffect(() => {
const beforeunloadHandle = () => {
return true;
};
window.addEventListener("beforeunload", beforeunloadHandle);
return () => {
window.removeEventListener("removeEventListener", beforeunloadHandle);
};
}, []);
Upvotes: 2