Reputation: 7755
My problem is that I need the user to confirm if he wants to continue to close or refresh the page. If he press No
, it won't close nor refresh the page.
Please take a look at my code so far:
useEffect(() => {
window.addEventListener("beforeunload", alertUser);
return () => {
window.removeEventListener("beforeunload", alertUser);
};
}, []);
Upvotes: 9
Views: 18027
Reputation: 46
I think this answer is pretty straightforward, using useEffect()
hook and window.onbeforeunload
, we can do this very easily
useEffect(() => {
window.onbeforeunload = () => true;
...
return () => {
window.onbeforeunload = null;
};
}, []);
This will ask the user everytime before hitting reload and leaving the site.
Upvotes: 1
Reputation: 42
I think you are looking for this.
https://dev.to/eons/detect-page-refresh-tab-close-and-route-change-with-react-router-v5-3pd
Browser Refresh, Closing Tab, and back and forward buttons, are all explained.
Try this:
useEffect(()=>{
const unloadCallback = (event) => {
const e = event || window.event;
//console.log(e)
e.preventDefault();
if (e) {
e.returnValue = ''
}
return '';
};
window.addEventListener("beforeunload", unloadCallback);
return () => {
//cleanup function
window.removeEventListener("beforeunload", unloadCallback);
}
},[])
Upvotes: -2
Reputation: 202686
If you want to display a sort of confirmation before leaving the page then follow the beforeunload event guidelines
According to the specification, to show the confirmation dialog an event handler should call preventDefault() on the event.
However note that not all browsers support this method, and some instead require the event handler to implement one of two legacy methods:
- assigning a string to the event's returnValue property
- returning a string from the event handler.
To combat unwanted pop-ups, browsers may not display prompts created in
beforeunload
event handlers unless the page has been interacted with, or may even not display them at all.The HTML specification states that calls to
window.alert()
,window.confirm()
, andwindow.prompt()
methods may be ignored during this event. See the HTML specification for more details.
I just tested this in chrome and safari and it works. I don't have a windows box, but this should cover most cases.
useEffect(() => {
const unloadCallback = (event) => {
event.preventDefault();
event.returnValue = "";
return "";
};
window.addEventListener("beforeunload", unloadCallback);
return () => window.removeEventListener("beforeunload", unloadCallback);
}, []);
Upvotes: 14