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.

7
  • 1
    you can't do Ctrl+Alt+Del, but you can do some non-reserved combos. Commented Mar 26, 2015 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. Commented Mar 26, 2015 at 20:32
  • How about Ctrl+Alt+ArrowKey? Commented Mar 26, 2015 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. Commented Mar 26, 2015 at 20:38
  • 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 stackoverflow.com/questions/5988230/… Commented Mar 26, 2015 at 20:55

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You could use jQuery see example below:

function keyPress(char) {
  jQuery.event.trigger({ type : 'keypress', which : char.charCodeAt(0) });
}

3 Comments

In firefox, pressing 'Shift+F2' opens developer toolbar, so will this code work to open developer toolbar by just simulating keypress event?
you can't press Shift or F2 with this code...
I thought you want ctrl, alt and arrowkey