Handling F5 in JQuery
I have a site where I would like to override F5 so that it doesn't refresh the page, but instead executes some ajax calls to refresh certain pieces. Is this possible?
EDIT: Because none of you seem to understand why I would want to do something like this, if you are genuinely interested then visit these links:
Open-source project (simple 开发者_运维技巧web-terminal): http://code.google.com/p/web-terminal
Running demo of simple web-terminal: http://web-terminal.net.pine.arvixe.com
Live implementation (The forum version): http://www.u413.com
Well, you could do that (at least in some browsers, I'm not sure if this works cross-browser), but it reaaalllly would be a pretty bad user experience.
$(document).bind('keypress keydown keyup', function(e) {
if(e.which === 116) {
console.log('blocked');
return false;
}
if(e.which === 82 && e.ctrlKey) {
console.log('blocked');
return false;
}
});
Anyway, even if that works, there are other ways for an user to refresh the site. Pressing ctrl + r
(cmd + r
) or just hit the refresh button. Well, the other hot-key combination can get blocked similar, but no way to block the refresh button.
--
It's maybe a huge better idea not to block those default browser behaviors, but to ask gracefully. That can be done by binding an event handler to the onbeforeunload
event, which fires before a site is unloaded.
$(window).bind('beforeunload', function() {
return 'Are you really sure?';
});
This is the same as the accepted answer above, except without capturing the 'keypress' event.
If you capture the 'keypress' event, you also block the 't' key. For some reason both the keycode and ASCII keycode are both captured if you use the 'keypress' event (which you can't see in the chrome debugger). The F5 key is '116', but the ASCII keycode for 't' is also 116, so with the 'keypress' event you block F5, but you also block 't' app-wide.
$(document).bind('keydown keyup', function(e) {
if(e.which === 116) {
console.log('blocked');
return false;
}
if(e.which === 82 && e.ctrlKey) {
console.log('blocked');
return false;
}
});
Here's the coffeescript just for fun :)
$(document).bind "keydown keyup", (e) ->
if e.keyCode is 116
console.log "blocked"
return false
if e.keyCode is 82 and e.ctrlKey
console.log "blocked"
false
Here's one example on how overriding the F5 key will enhance user experience. I'm building the newsletter editor for my client and I need to prevent the page from reloading when user accidentally presses F5 key but instead it refreshes email preview created from entered html code.
精彩评论