Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 231
Chev Avatar asked Jan 24 '11 22:01

Chev


2 Answers

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?';
});
like image 161
jAndy Avatar answered Nov 09 '22 17:11

jAndy


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
like image 9
nomis Avatar answered Nov 09 '22 17:11

nomis