I would like to prevent an HTML page refresh (given a variable refreshMode != 1
):
window.onbeforeunload = function(e) {
if(refreshMode == 1){
return;
}else{
// don't do it!
e.preventDefault();
}
};
I have tried e.preventDefault()
and e.stopPropagation()
, but neither appears to be preventing the refresh from submit the request.
Is it possible to do this?
I would like to prevent an HTML page refresh (given a variable refreshMode != 1
):
window.onbeforeunload = function(e) {
if(refreshMode == 1){
return;
}else{
// don't do it!
e.preventDefault();
}
};
I have tried e.preventDefault()
and e.stopPropagation()
, but neither appears to be preventing the refresh from submit the request.
Is it possible to do this?
Share Improve this question edited Jan 7, 2023 at 1:52 Paolo 21.2k21 gold badges76 silver badges121 bronze badges asked Aug 15, 2020 at 15:48 JimJim 2411 gold badge3 silver badges10 bronze badges 9- I have never done this by this way but there is others like using Ajax. If you are trying to do a one-page website I remend looking reactjs navigation. – Victor Molina Commented Aug 15, 2020 at 15:51
-
did you try
return false
? – Dominik Matis Commented Aug 15, 2020 at 15:52 -
Try
return true
: jsfiddle/ydbnuvt1 – Will Commented Aug 15, 2020 at 15:52 - 1 Does this answer your question? Prevent a webpage from navigating away using JavaScript – luk2302 Commented Aug 15, 2020 at 15:52
- e.preventDefault(); should work if you are handling the submit of a form through "onSubmit()", you doing that? – Menawer Commented Aug 15, 2020 at 15:58
1 Answer
Reset to default 4Set a return value in additiont o preventing default. You cannot change the prompt text (that used to be possible), and you cannot prevent the prefresh if the user confirms on the prompt.
See https://developer.mozilla/en-US/docs/Web/API/Window/beforeunload_event
window.addEventListener('beforeunload', (event) => {
// Cancel the event as stated by the standard.
event.preventDefault();
// Chrome requires returnValue to be set.
event.returnValue = '';
});