1

Is it possible to simulate key press using JavaScript? For example, How can I simulate Ctrl+Alt+ArrowKey? I want to simulate special keys. Is there any API/Framework available?

Lets say, I am building a web based virtual keyboard.

  • 1
    you can't do Ctrl+Alt+Del, but you can do some non-reserved combos. – dandavis Mar 26 '15 at 20:30
  • Like Dandavis said, you cant simulate ctrl-alt-delete (and why would you need to on a web app?) but you can use testing frameworks like Protractor to help you do end to end testing. – David says Reinstate Monica Mar 26 '15 at 20:32
  • How about Ctrl+Alt+ArrowKey? –  Mar 26 '15 at 20:35
  • generally, you can only do key combos that the OS and/or browser is not using already. ctrl+alt+W would be ok, but not an OS shortcut like Ctrl+Alt+arrow. when you simulate a key in JS, it's only for the benefit of JS reacting to keypresses on the page, with very few exceptions. in short, you cannot cause any special reactions to simulated keys, other than reactions you coded yourself. – dandavis Mar 26 '15 at 20:38
  • In firefox, 'Shift+F2' opens developer toolbar, so you mean to say I cannot open developer toolbar via javascript code by simulating keypress event? –  Mar 26 '15 at 20:45
  • 1
    What you are asking for is an analog of a sendKeys function. Sending keystrokes to the keyboard buffer is an entirely different thing than sending keys to DOM handlers. Allowing the former would be a horrible security issue. @see http://stackoverflow.com/questions/5988230/can-i-do-sendkeys-in-javascript – mccainz Mar 26 '15 at 20:55
  • @Andy: that's exactly what i'm saying. honestly, you might be able to find a few holes in the fence for various keys in various browsers/OSs, but nothing dependable. – dandavis Mar 26 '15 at 20:57

2 Answers2

1

If your goal is to achieve a browser analog of a sendKeys function (a function where you send keystrokes directly to the keyboard buffer) then you will be unable to achieve this. Triggering key events in a browser sends events to DOM handlers not the keyboard buffer. For this reason simulating an actual working keyboard in the browser which sends strokes to the keyboard buffer is impossible without a security breaching hole from the browser into the OS.

mccainz
  • 3,478
  • 5
  • 35
  • 45
0

You could use jQuery see example below:

function keyPress(char) {
  jQuery.event.trigger({ type : 'keypress', which : char.charCodeAt(0) });
}
Kevin Crain
  • 1,905
  • 1
  • 19
  • 28