我知道不建议这样做,但我需要它,因为我在页面中有一个 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:
Firefox 提示(你可以看出我在 Mac 上测试过)
IE7 &IE8 提示
IE9 提示
结束:
是的,我没有测试 IE6,我删除了安装了它的 VM,我没有安装 IE10 beta 的 VM,所以你也不走运.
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;可能会揭示一些有用的东西.我不同意 Jordan 的回复,即您不应该尝试覆盖默认值,所以我在这里结束我的实验.
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 刷新/重新加载页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!