How to detect user has click the Reload button on the browser:
I am trying to use the useBeforeunload
library and javascript listener method beforeunload
to detect however the event.preventDefault()
and set the return value to false
still doesn't do anything instead it keeps reloading the page even though I put some Modal
tag to notify user that your going to reload the page and it did popup the modal right after I hit the Reload button but it force to reload the page. I also have issue in terms of detecting the Ctrl + Shift + R it seems it didn't detect for some reason even though I tried to capture it using keydown
listener. What I wanted to achieve is to prevent it from reloading the page and show the modal to notify the user. Please see my code below:
App.jsx
const [show, setShow] = useState(false);
const onClose = () => setShow(false); // this will show the modal
const disableF5 = ((e) => {
if(window.location.pathname.includes('/apple/')) {
if(!config.enableRefresh) {
if (e.which === 116 || e.keyCode === 116 || (e.key === "r" && e.ctrlKey) || (e.key === "r" && e.shiftKey && e.ctrlKey)) { // ctrl + shift + r never detected
e.preventDefault();
setShow(true);
return;
}
}
}
});
const handleReloadCancel = useBeforeunload(event => {
event.preventDefault(); // this should prevent it from reloading the page
setShow(true)
});
useEffect(() => {
window.addEventListener('keydown', disableF5);
window.addEventListener('beforeunload', handleReloadCancel);
return () => {
window.removeEventListener('keydown', disableF5);
window.removeEventListener('beforeunload', handleReloadCancel);
}
}, [])
I also tried using this method window.performance.navigation.type == 1
but it didn't help as well. Any ideas on how to achieve my goal? Thanks!