0

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?

Paolo
  • 20,112
  • 21
  • 72
  • 113
Jim
  • 201
  • 3
  • 10
  • 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 recommend looking reactjs navigation. – Victor Molina Aug 15 '20 at 15:51
  • did you try `return false` ? – Dominik Matis Aug 15 '20 at 15:52
  • Try `return true`: https://jsfiddle.net/ydbnuvt1/ – Will Aug 15 '20 at 15:52
  • 1
    Does this answer your question? [Prevent a webpage from navigating away using JavaScript](https://stackoverflow.com/questions/821011/prevent-a-webpage-from-navigating-away-using-javascript) – luk2302 Aug 15 '20 at 15:52
  • e.preventDefault(); should work if you are handling the submit of a form through "onSubmit()", you doing that? – Menawer Aug 15 '20 at 15:58
  • Dominik, seemed to work first time I tried only. – Jim Aug 15 '20 at 16:43
  • Will, this works but is there a way to prevent the popup prompt? If I cancel it doesn't refresh but I want that to be the default behavior, without being prompted. – Jim Aug 15 '20 at 16:44
  • Menawer, no. This is when the user hit refresh on browser button i.e. F5 – Jim Aug 15 '20 at 16:45
  • luk2302, yes this works but still I get the popup. I want to prevent the prompt, too... so I don't have to click cancel to prevent refresh. If refreshMode is 0, then don't prompt and don't refresh. – Jim Aug 15 '20 at 16:47

1 Answers1

1

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 = '';
});
xdumaine
  • 10,096
  • 6
  • 62
  • 103
  • Ok, yes that works, but I don't want the prompt. If refreshMode is off, then don't refresh and don't prompt user. – Jim Aug 15 '20 at 16:51
  • 3
    Sorry that's not possible in the browser. – xdumaine Aug 16 '20 at 01:43
  • @Jim that is obviously not possible, do you think it is a good idea to let spam / ad sites trap you one their site preventing you from leaving it? – luk2302 Aug 16 '20 at 13:36
  • @luk2302 a refresh click isn't meant to take you away, though. – Jim Aug 17 '20 at 19:58