简体   繁体   English

禁用页面刷新

[英]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(); 为了防止页面刷新,我可以使用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. JavaScript无法阻止用户离开页面(刷新算作离开页面),因为它会侵犯用户的……无论如何……无论如何,这是不可能的。 (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.onBeforeUnload事件处理程序请求确认。

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. 请注意,处理函数应将字符串值分配给Event对象的returnValue属性,并返回相同的字符串。 For more information see MDN WindowEventHandlers.onbeforeunload . 有关更多信息,请参见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). 如果不需要保留太多数据,则可以输入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. 哦,您还可以考虑使用AJAX的最后状态来存储数据服务器端并向用户提供页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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