Reputation: 231
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?
Upvotes: 3
Views: 11553
Reputation: 10329
Set 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.org/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 = '';
});
Upvotes: 4