简体   繁体   中英

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...???

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).

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 .

但是,如果您将使用HTML5中的pushState / replaceState直观地存储Web应用程序的状态(并将服务器设置为通过所有这些url提供服务),即使刷新后也可以将用户导航到应用程序的正确位置。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM