Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent a browser page refresh in JavaScript?

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?

like image 365
Jim Avatar asked Oct 15 '25 17:10

Jim


1 Answers

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 = '';
});
like image 145
xdumaine Avatar answered Oct 18 '25 20:10

xdumaine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!