【问题标题】:Prevent user from refreshing the page阻止用户刷新页面
【发布时间】:2017-01-17 14:50:03
【问题描述】:

我想阻止用户刷新页面,怎么做?我一直在使用e.preventDefault 方法,但它运行不正常。

【问题讨论】:

  • 请分享你的作品。
  • 实际上,你不能。即使可以,也不应该。
  • 您需要在您的活动中正确发送e,如下所示:$(someElement).someAction(function(e){}); 或在您的方法末尾使用return false
  • 为什么要破坏用户的浏览器功能?
  • @JonStirling 感谢提醒

标签: javascript jquery html refresh preventdefault


【解决方案1】:

HTML 规范规定作者应该使用Event.preventDefault() 方法而不是使用Event.returnValue 来提示用户。

window.addEventListener('beforeunload', function (e) {
  // Cancel the event
  e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
  // Chrome requires returnValue to be set
  e.returnValue = '';
});

参考:WindowEventHandlers.onbeforeunload

【讨论】:

    【解决方案2】:

    尝试类似:

    <script type="text/javascript">
        // Callback
        window.onbeforeunload = function(e) {
            // Turning off the event
            e.preventDefault();
        }
    </script>
    

    关于这些功能的一些基本解释

    防止默认值: http://www.w3schools.com/jsref/event_preventdefault.asp

    卸载前: http://www.w3schools.com/jsref/event_onbeforeunload.asp

    【讨论】:

      【解决方案3】:

      你甚至可以使用 window.onbeforeunload。

      window.onbeforeunload = function() {
                  return "you can not refresh the page";
              }
      

      【讨论】:

      • window.onbeforeunload = function(event) { event.returnValue = "在这里写些聪明的东西.."; };
      • 我试过这个方法 window.onbeforeunload = function(event) { event.returnValue = "Write something smart here.."; };但它不适用于 chrome。
      猜你喜欢
      • 2019-10-06
      • 2015-08-10
      • 2014-10-15
      • 2010-11-17
      • 1970-01-01
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多