Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 463
zproject89 Avatar asked May 15 '26 21:05

zproject89


1 Answers

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);
}
like image 188
Dropout Avatar answered May 18 '26 09:05

Dropout



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!