防止页面刷新过多js_防止使用JavaScript刷新/重新加载页面

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.

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.

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

解决方案

UPDATE: I wrote this 5 years ago, browsers do different stuff now, you can still use this for testing your browser set, but your experience may vary from my old research.

Experimenting using jQuery, because I'm lazy.

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.

$('p').append(Math.random());

$(window).bind({

beforeunload: function(ev) {

ev.preventDefault();

},

unload: function(ev) {

ev.preventDefault();

}

});

Using CTRL-R or F5 or Reload Button:

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

IE7 & IE8: Shows a prompt with two buttons:

OK - Reloads the page

Cancel - Does not reload the page

IE9: Shows a prompt with two buttons:

Leave this page - reloads

Stay on this page - does not reload

Firefox Prompt (you can tell I tested it on a Mac)

IE7 & IE8 Prompt

IE9 Prompt

In closing:

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值