Catch “Command+R” in Safari with JQuery

2019-08-10 16:45发布

I need to intercept the browser-reload-functionality in Safari (I know this is usually not something one should do, but in my case this makes sense).

For Windows I just do this:

$(document).keydown(function(event) {
    if ( event.which == 116 ) {
        restart();
        return false;
    }
});

Do I need to use a JQuery Plugin to capture two Keys at the same time or is this already implemented in JQuery in some form?

Also, are the keycodes under Mac the same as they are under windows? ("Command" being the keycode "17" and "r" being "19"?) or is it "55" for the command key and "15" for "r"?

(using this source: http://boredzo.org/blog/archives/2007-05-22/virtual-key-codes

3条回答
一纸荒年 Trace。
2楼-- · 2019-08-10 17:26

There is a Jquery plugin to capture keyboard events and th best part is that it will allow you to handle the key events with their names. like if you want to capture CTRL + R then you need not to worry about the key codes, the plugin will handle this by itself.

Check it out here: https://keithamus.github.io/jwerty/

查看更多
女痞
3楼-- · 2019-08-10 17:27

You can catch + R on Mac using the next code:

$(document).on( 'keydown', function(event){
    if( event.which === 82 && event.metaKey ) {
        alert( 'Your changes will be lost, are you sure to refresh?' );
    }
});

.metaKey stands for on Mac and key on PC.

查看更多
唯我独甜
4楼-- · 2019-08-10 17:28

I think I figured it out without having to use a plugin. I'll verify if it also works on the Mac later (I don't own one), but it works for CTRL+R on a PC:

var keys = {};

$(document).ready(function(){
    $(document).keydown(function(event) {
        keys[event.which] = true;

        //CTRL+R on a PC    
        if(keys[17] && keys[82])
        {
            restart();
            return false;
        }   

        //COMMAND+R an a Mac    
        if(keys[81] && keys[91])
        {
            restart();
            return false;
        }       
    });

    $(document).keyup(function (event) {
        delete keys[event.which];
    });
});

This one helped me get there: Can jQuery .keypress() detect more than one key at the same time?

查看更多
登录 后发表回答