Overriding Browser's Keyboard Shortcuts

Javascript

Javascript Problem Overview


I'd like to add support for keyboard shortcuts to a couple of pages in my web application by intercepting the keypress event handler of the document object, not the accesskey attribute.

The problem is that every browser has its own keyboard combinations, so it's impossible to come up with a set of keyboard combinations that work on all web browsers and yet consistent.(e.g. It'd be silly if the shortcut for save was Ctrl + Shift + S while one for delete was Alt + D.)

So I figured it would be just simpler to override browser shortcuts altogether in a couple of pages with mine.

All downside aside, is it possible? If so, how do you do it?

Javascript Solutions


Solution 1 - Javascript

onkeydown = function(e){
  if(e.ctrlKey && e.keyCode == 'S'.charCodeAt(0)){
    e.preventDefault();
    //your saving code
  }
}

Solution 2 - Javascript

There's an excellent coverage of this here: http://unixpapa.com/js/key.html

As for whether this is something that should be done, stackoverflow's question editor override's quite a few keys without disrupting too much (hover over the toolbar buttons).

Solution 3 - Javascript

Here is my solution to this problem:

Most (if not all) of the browser's shortcuts will be overriden. Only system ones, like Alt + Tab or the Windows key won't.

document.onkeydown = overrideKeyboardEvent;
document.onkeyup = overrideKeyboardEvent;
var keyIsDown = {};

function overrideKeyboardEvent(e){
  switch(e.type){
    case "keydown":
      if(!keyIsDown[e.keyCode]){
        keyIsDown[e.keyCode] = true;
        // do key down stuff here
      }
    break;
    case "keyup":
      delete(keyIsDown[e.keyCode]);
      // do key up stuff here
    break;
  }
  disabledEventPropagation(e);
  e.preventDefault();
  return false;
}
function disabledEventPropagation(e){
  if(e){
    if(e.stopPropagation){
      e.stopPropagation();
    } else if(window.event){
      window.event.cancelBubble = true;
    }
  }
}

Solution 4 - Javascript

Here is my Solution:

document.onkeydown = function () {
                       if ((window.event.keyCode == 121) && (window.event.ctrlKey))) {
               window.event.returnValue = false;
               window.event.cancelBubble = true;
               window.event.keyCode = 0;
               return false;
           }
       }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTom TuckerView Question on Stackoverflow
Solution 1 - Javascriptantimatter15View Answer on Stackoverflow
Solution 2 - JavascriptBrad RobinsonView Answer on Stackoverflow
Solution 3 - JavascriptAleskView Answer on Stackoverflow
Solution 4 - JavascriptdeepeshbView Answer on Stackoverflow