El Classico
El Classico

Reputation: 29

Disable page refresh

I need to prevent users from refreshing a page.

  1. I have scripted in such a way that there is no 'forward' or 'backward' movement required.
  2. However, if one refreshes the page, 'everything' starts from the beginning.
    • To save everything before page refresh and restore them after is not ideal.
  3. In order to prevent page refresh, I could use an alert();, but there are chances that the user might neglect the warning.
  4. Any other choices...???

Upvotes: 0

Views: 2616

Answers (4)

Readren
Readren

Reputation: 1240

The best thing you can do is to ask for a confirmation by means of the window.onBeforeUnload event handler.

window.addEventListener('beforeUnload', function(e) {
  var dialogText = 'Dialog text here';
  e.returnValue = dialogText;
  return dialogText;
});

Note that the handler function should assign a string value to the returnValue property of the Event object and return the same string. For more information see MDN WindowEventHandlers.onbeforeunload.

Upvotes: 0

Llamageddon
Llamageddon

Reputation: 3526

There is no way to prevent the user from refreshing the page. If you do not require that much data to be preserved, you can put in the URL (site.com/page.php?sort=2&x=3&y=4).

If you need a lot of data, you can only hope the user doesn't refresh the page. One way would be to, as you noted, display a dialog.

Oh, guess you could also use AJAX to store data server side and serve page to the user considering it's last state.

Upvotes: 0

user1046334
user1046334

Reputation:

But if you will use pushState / replaceState from HTML5 to visually store the state of your webapp (and set the server to serve it from all those urls), you can navigate the user to the right place of an app even after refresh.

Upvotes: 0

Madara's Ghost
Madara's Ghost

Reputation: 174957

JavaScript cannot prevent the user from leaving the page (refresh counts as leaving the page), as it would violate the user's... whatever... Anyway, it's not possible. (even if you try, the browser will have tools to easily bypass any script you may write).

Upvotes: 1

Related Questions