Reputation: 29
I need to prevent users from refreshing a page.
alert();
, but there are chances that the user might neglect the warning.Upvotes: 0
Views: 2616
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
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
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
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