zproject89
zproject89

Reputation: 245

Javascript how to listen keyboard shortcut?

I try to use javascript listen the shortcut of keyboard, such as "command+shift+4"
My current solution is : [on Mac]

window.addEventListener('keypress', function(e){
    if (e.shiftKey && e.metaKey && e.keyCode == 52) {
        alert("Here it is.");
    }
}, false);

But since the shortcut "command+shift+4" is the default "screenshot" of Mac, so the javascript can not capture it. If I change the 52 to 53, then this code works, but it listens to "command+shift+5".
Is there some solution let javascript listen to the default shortcut of Mac?

Upvotes: 3

Views: 10596

Answers (1)

Dropout
Dropout

Reputation: 13866

Your browser is running underneath your operating system. If you "catch" the keypress event on the OS level and don't let it pass through ( imagine e.stopPropagation() ), you are unable to catch it in your browser. It's the same thing as if you were trying to bind something to Alt+F4 - this event is handled before it gets to the browser's on-page events. Some may pass through and some might not.

If you are able to, change the shortcut to a OS/browser independent one. Avoid these keyboard shortcuts. Also you might want to read this SO question.

To make sure your shortcut is recognized correctly simply do an output of your keypress

window.onkeyup = function(e){
    var pressed = "";
    if(e.shiftKey){
        pressed += " + Shift";
    }else if(e.ctrlKey){
        pressed += " + Ctrl";
    } //and so on
    pressed += e.keyCode;
    console.log(pressed);
}

Upvotes: 4

Related Questions