繁体   English   中英

PHP / JavaScript防止页面重新加载/刷新

[英]php/javascript prevent page reload/refresh

在我的项目中,我有一个php页面,我想在该页面中重新加载浏览器或F5,从而将页面重定向到另一个页面。 我插入了以下代码:

<script type="text/javascript">
window.onbeforeunload = function() {
    window.location.href = "../index.html";
}
</script>

如果代替window.location.href指令,我插入一个alert(“ test”); 该代码运行,但是使用我的代码以防刷新,该页面无法重定向到index.html。 为什么?

您可以捕获F5CTRL + R的按键并在重定向之前处理事件。 虽然更改任何默认浏览器行为都可能被网站用户认为是邪恶的 ,但更令人讨厌。

在这里,我提供了一个示例功能来处理用户尝试刷新页面时的重定向。 http://jsfiddle.net/dQEeW/

它的核心以及处理位置更改的方法是此事件绑定。

$(document).bind('keydown', function( event ){
        if( event !== undefined ) {
          if( (event.keyCode == 82 &&
                event.ctrlKey
               ) || (event.keyCode == 116) 
            ) {
              event.keyCode = 0;

              if(destination) window.location.href =  destination;

            return !destination; //false if destination was set true otherwise.
          }
        }
    });

该函数基于另一个SO答案,但我将其限制为仅处理F5,并对其进行了扩展以处理CTRL + R。 但是,您只能限制键盘驱动的刷新。

另一个SO答案中提取信息,您可能希望捕获页面卸载并返回一个字符串,以警告用户他们正在尝试执行原本没有设计的操作。

window.onbeforeunload = confirmExit;
  function confirmExit()
  {
      return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
  }

这应该使您有机会解决他们想离开的原因,并有机会取消他们。

暂无
暂无

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

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