Catch “Command+R” in Safari with JQuery

我与影子孤独终老i 提交于 2019-12-11 06:25:46

问题


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


回答1:


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/




回答2:


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?




回答3:


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.



来源:https://stackoverflow.com/questions/7738139/catch-commandr-in-safari-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!