防止使用JavaScript刷新/重新加载页面 [英] Prevent refreshing / reloading a page with JavaScript

查看:2078
本文介绍了防止使用JavaScript刷新/重新加载页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是不推荐的,但是我需要它,因为我有一个iframe内部的页面谁有实际的内容,我想要当用户点击刷新按钮,iframe重新加载不是整个页面。

I know this is not recommended, but I need it because I have an iframe inside the page who has the actual content and I want that when the users hits refresh button, iframe reloads not entire page.

我知道我必须调用 onunload / onbeforeunload 事件,不想问我是否要离开窗户,只是不要。

I know I have to call onunload / onbeforeunload event, but I don't want to ask me if I want to leave the window, just don't.

可以吗?我已经处理了F5键,但我也想防止按钮刷新。

Is that possible? I've got handled the F5 key, but I like to prevent refreshing from button too.

推荐答案

更新:我5年前写的这个浏览器现在做不同的东西,你仍然可以用这个来测试你的浏览器,但你的经验可能会有所不同,我的旧研究。

使用jQuery进行实验,因为我很懒惰。

Experimenting using jQuery, because I'm lazy.

理论上,防止默认行为应该阻止事件做任何它应该做的事情。它不适用于我的示例中的事件,并且在不同的浏览器中具有不同的结果。我把Math.random()放入,以确定页面是否已被重新加载。因为不同的浏览器做不同的事情,我强烈建议不要在生产环境中使用它。

Theoretically, preventing the default behavior should stop the event from doing whatever it is supposed to do. It doesn't work with the events in my example and has different results in different browsers. I put the Math.random() in to determine if the page has been reloaded or not. Because different browsers do different things, I highly recommend NOT using this in a production environment.

<body>
<p></p>
<script type="text/javascript">
    $('p').append(Math.random());

    $(window).bind({
        beforeunload: function(ev) {
            ev.preventDefault();
        },
        unload: function(ev) {
            ev.preventDefault();
        }
    });
</script>
</body>

使用CTRL-R或F5或重新加载按钮:

Using CTRL-R or F5 or Reload Button:


  • Safari:没有任何

  • Chrome:没有任何

  • Opera 10& 11:不做任何

  • Firefox 7.x:显示一个带有两个按钮的特殊提示:


    • 不重新加载页面

    • 离开页面 - 重新加载页面

    • Safari: Does nothing
    • Chrome: Does nothing
    • Opera 10 & 11: Does nothing
    • Firefox 7.x: Shows a special prompt with two buttons:
      • Stay on Page - Does not reload page
      • Leave Page - Reloads the page

      • 确定 - 重新加载页面

      • 取消 - 不重新加载页面


      • 留下此页面 - 重新加载

      • 留在本页 - 不重新加载

      Firefox提示(您可以告诉我在Mac上测试过)

      IE7& IE8提示

      IE9提示

      关闭:

      是的,我没有测试IE6,我删除了安装了它的虚拟机,我没有安装有IE10测试版的虚拟机,所以你也没有运气。

      Yes, I did not test IE6, I deleted my VM which had it installed, I don't have a VM with IE10 beta installed, so you're out of luck on that too.

      您也可以尝试使用cancelBubble和stopPropagation,或者返回false;可能会显示有用的东西我在约旦的回复中说,你不应该试图覆盖默认值,所以我在这里结束我的实验。

      You might also experiment with cancelBubble and stopPropagation or maybe return false; might reveal something useful. I'm down with Jordan's reply that you shouldn't be trying to override the defaults, so I'm concluding my experiment here.

      这篇关于防止使用JavaScript刷新/重新加载页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆