最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

listener - Javascript how to listen keyboard shortcut? - Stack Overflow

programmeradmin0浏览0评论

I try to use javascript listen the shortcut of keyboard, such as "mand+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 "mand+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 "mand+shift+5".
Is there some solution let javascript listen to the default shortcut of Mac?

I try to use javascript listen the shortcut of keyboard, such as "mand+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 "mand+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 "mand+shift+5".
Is there some solution let javascript listen to the default shortcut of Mac?

Share Improve this question asked Apr 15, 2014 at 5:18 zproject89zproject89 2451 gold badge5 silver badges19 bronze badges 2
  • 1 The priority is the operating system. If that allows to bubble the event - you can listen on. Otherwise, sorry :( Can you imagine ALT+F4 being stopped by Javascript? that would be at the least extremely annoying. – Unamata Sanatarai Commented Apr 15, 2014 at 5:22
  • It is up to the host which events it dispatches into a document. If the document doesn't get an event, it can't respond. – RobG Commented Apr 15, 2014 at 5:24
Add a ment  | 

1 Answer 1

Reset to default 4

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);
}
发布评论

评论列表(0)

  1. 暂无评论