Home » Jquery » javascript – Is it possible to simulate key press events programmatically?-Exceptionshub

javascript – Is it possible to simulate key press events programmatically?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment


Is it possible to simulate key press events programmatically in JavaScript?

How to&Answer:

A non-jquery version that works in both webkit and gecko:

var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";

  "keydown", // event type: keydown, keyup, keypress
  true,      // bubbles
  true,      // cancelable
  window,    // view: should be window
  false,     // ctrlKey
  false,     // altKey
  false,     // shiftKey
  false,     // metaKey
  40,        // keyCode: unsigned long - the virtual key code, else 0
  0          // charCode: unsigned long - the Unicode character associated with the depressed key, else 0


If you are ok to use jQuery 1.3.1:

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

$(function() {
  $('body').keypress(function(e) {



What you can do is programmatically trigger keyevent listeners by firing keyevents. It makes sense to allow this from a sandboxed security-perspective. Using this ability, you can then apply a typical observer-pattern. You could call this method “simulating”.

Below is an example of how to accomplish this in the W3C DOM standard along with jQuery:

function triggerClick() {
  var event = new MouseEvent('click', {
    'view': window,
    'bubbles': true,
    'cancelable': true
  var cb = document.querySelector('input[type=submit][name=btnK]'); 
  var canceled = !cb.dispatchEvent(event);
  if (canceled) {
    // preventDefault was called and the event cancelled
  } else {
    // insert your event-logic here...

This example is adapted from: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

In jQuery:

    type: 'keypress',
    which: character.charCodeAt(0 /*the key to trigger*/)      

But as of recently, there is no [DOM] way to actually trigger keyevents leaving the browser-sandbox. And all major browser vendors will adhere to that security concept.

As for plugins such as Adobe Flash – which are based on the NPAPI-, and permit bypassing the sandbox: these are phasing-out ; Firefox.

Detailed Explanation:

You cannot and you must not for security reasons (as Pekka already pointed out). You will always require a user interaction in between. Additionally imagine the chance of the browser vendors getting sued by users, as various programmatic keyboard events will have led to spoofing attacks.

See this post for alternatives and more details. There is always the flash based copy-and-paste. Here is an elegant example. At the same time it is a testimony why the web is moving away from plugin vendors.

There is a similar security mindset applied in case of the opt-in CORS policy to access remote content programmatically.

The answer is:
There is no way to programmatically trigger input keys in the sandboxed browser environment under normal circumstances.

Bottomline: I am not saying it will not be possible in the future, under special browser-modes and/or privileges towards the end-goal of gaming, or similar user-experiences. However prior to entering such modes, the user will be asked for permissions and risks, similar to the Fullscreen API model.

Useful: In the context of KeyCodes, this tool and keycode mapping will come in handy.

Disclosure: The answer is based on the answer here.


You can dispatch keyboard events on an element like this

element.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));


You can use dispatchEvent():

function simulateKeyPress() {
  var evt = document.createEvent("KeyboardEvent");
  evt.initKeyboardEvent("keypress", true, true, window,
                    0, 0, 0, 0,
                    0, "e".charCodeAt(0))
  var body = document.body;
  var canceled = !body.dispatchEvent(evt);
  if(canceled) {
    // A handler called preventDefault
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");

I didn’t test this, but it’s adapted from the code on dispatchEvent()’s documentation. You’ll probably want to read through that, and also the docs for createEvent() and initKeyEvent().


You can create and dispatch keyboard events, and they will trigger appropriate registered event handlers, however they will not produce any text, if dispatched to input element for example.

To fully simulate text input you need to produce a sequence of keyboard events plus explicitly set the text of input element. The sequence of events depends on how thoroughly you want to simulate text input.

The simplest form would be:



Building on the answer from alex2k8, here’s a revised version that works in all browsers that jQuery supports (the problem was in missing arguments to jQuery.event.trigger, which is easy to forget when using that internal function).

// jQuery plugin. Called on a jQuery object, not directly.
jQuery.fn.simulateKeyPress = function (character) {
  // Internally calls jQuery.event.trigger with arguments (Event, data, elem).
  // That last argument, 'elem', is very important!
  jQuery(this).trigger({ type: 'keypress', which: character.charCodeAt(0) });

jQuery(function ($) {
  // Bind event handler
  $('body').keypress(function (e) {
  // Simulate the key press

You could even push this further and let it not only simulate the event but actually insert the character (if it is an input element), however there are many cross-browser gotcha’s when trying to do that. Better use a more elaborate plugin like SendKeys.


In some cases keypress event can’t provide required funtionality. From mozilla docs we can see that the feature is deprecated:

This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

So, since the keypress event is combined from the two consequently fired events keydown, and the following it keyup for the same key, just generate the events one-by-one:

element.dispatchEvent(new KeyboardEvent('keydown',{'key':'Shift'}));
element.dispatchEvent(new KeyboardEvent('keyup',{'key':'Shift'}));


For those interested, you can, in-fact recreate keyboard input events reliably. In order to change text in input area (move cursors, or the page via an input character) you have to follow the DOM event model closely: http://www.w3.org/TR/DOM-Level-3-Events/#h4_events-inputevents

The model should do:

  • focus (dispatched on the DOM with the target set)

Then for each character:

  • keydown (dispatched on the DOM)
  • beforeinput (dispatched at the target if its a textarea or input)
  • keypress (dispatched on the DOM)
  • input (dispatched at the target if its a textarea or input)
  • change (dispatched at the target if its a select)
  • keyup (dispatched on the DOM)

Then, optionally for most:

  • blur (dispatched on the DOM with the target set)

This actually changes the text in the page via javascript (without modifying value statements) and sets off any javascript listeners/handlers appropriately. If you mess up the sequence javascript will not fire in the appropriate order, the text in the input box will not change, the selections will not change or the cursor will not move to the next space in the text area.

Unfortunately the code was written for an employer under an NDA so I cannot share it, but it is definitely possible but you must recreate the entire key input “stack” for each element in the correct order.


This approach support cross-browser changing the value of key code.

var $textBox = $("#myTextBox");

var press = jQuery.Event("keypress");
press.altGraphKey = false;
press.altKey = false;
press.bubbles = true;
press.cancelBubble = false;
press.cancelable = true;
press.charCode = 13;
press.clipboardData = undefined;
press.ctrlKey = false;
press.currentTarget = $textBox[0];
press.defaultPrevented = false;
press.detail = 0;
press.eventPhase = 2;
press.keyCode = 13;
press.keyIdentifier = "";
press.keyLocation = 0;
press.layerX = 0;
press.layerY = 0;
press.metaKey = false;
press.pageX = 0;
press.pageY = 0;
press.returnValue = true;
press.shiftKey = false;
press.srcElement = $textBox[0];
press.target = $textBox[0];
press.type = "keypress";
press.view = Window;
press.which = 13;



just use CustomEvent

     var event=new CustomEvent(type);
     for(var p in options){

4 ex want to simulate ctrl+z

     if(ev.ctrlKey && ev.keyCode === 90) console.log(ev); // or do smth



Here’s a library that really helps: https://cdn.rawgit.com/ccampbell/mousetrap/2e5c2a8adbe80a89050aaf4e02c45f02f1cc12d4/tests/libs/key-event.js

I don’t know from where did it came from, but it is helpful. It adds a .simulate() method to window.KeyEvent, so you use it simply with KeyEvent.simulate(0, 13) for simulating an enter or KeyEvent.simulate(81, 81) for a 'Q'.

I got it at https://github.com/ccampbell/mousetrap/tree/master/tests.


This worked for me and it does simulate a keyup for my textaera. if you want it for the entire page just put the KeySimulation() on <body> like this <body onmousemove="KeySimulation()"> or if not onmousemove then onmouseover or onload works too.

function KeySimulation()
var e = document.createEvent("KeyboardEvent");
if (e.initKeyboardEvent) {  // Chrome, IE
    e.initKeyboardEvent("keyup", true, true, document.defaultView, "Enter", 0, "", false, "");
} else { // FireFox
    e.initKeyEvent("keyup", true, true, document.defaultView, false, false, false, false, 13, 0);

<input type="button" onclick="KeySimulation();" value=" Key Simulation " />
<textarea id="MyTextArea" rows="15" cols="30"></textarea>


As of 2019, this solution has worked for me:

  new KeyboardEvent("keydown", {
    keyCode: 69, // example values
    code: "KeyE" // put everything you need in this object

I used this in my browser game, in order to support mobile devices with a simulated keypad.


Here is a solution that works in Chrome and Chromium (have only tested these platforms). It seems Chrome has some bug or own approach to handling key codes so this property has to be added separately to the KeyboardEvent.

function simulateKeydown (keycode,isCtrl,isAlt,isShift){
    var e = new KeyboardEvent( "keydown", { bubbles:true, cancelable:true, char:String.fromCharCode(keycode), key:String.fromCharCode(keycode), shiftKey:isShift, ctrlKey:isCtrl, altKey:isAlt } );
    Object.defineProperty(e, 'keyCode', {get : function() { return this.keyCodeVal; } });     
    e.keyCodeVal = keycode;


It was single rowed once due to easy usage in a console context. But probably useful still.

    var pressthiskey = "q"/* <-- q for example */;
    var e = new Event("keydown");
    e.key = pressthiskey;
    e.keyCode = e.key.charCodeAt(0);
    e.which = e.keyCode;
    e.altKey = false;
    e.ctrlKey = true;
    e.shiftKey = false;
    e.metaKey = false;
    e.bubbles = true;


This is what I managed to find:

function createKeyboardEvent(name, key, altKey, ctrlKey, shiftKey, metaKey, bubbles) {
  var e = new Event(name)
  e.key = key
  e.keyCode = e.key.charCodeAt(0)
  e.which = e.keyCode
  e.altKey = altKey
  e.ctrlKey = ctrlKey
  e.shiftKey = shiftKey
  e.metaKey =  metaKey
  e.bubbles = bubbles
  return e

var name = 'keydown'
var key = 'a'

var event = createKeyboardEvent(name, key, false, false, false, false, true)

document.addEventListener(name, () => {})


Native JavaScript with TypeScript supported solution:

Type the keyCode or whichever property you are using and cast it to KeyboardEventInit


const event = new KeyboardEvent("keydown", {
          keyCode: 38,
        } as KeyboardEventInit);


as soon as the user presses the key in question you can store a reference to that even and use it on any HTML other element:

EnterKeyPressToEmulate<input class="lineEditInput" id="addr333_1" type="text" style="width:60%;right:0%;float:right" onkeydown="keyPressRecorder(event)"></input>
TypeHereToEmulateKeyPress<input class="lineEditInput" id="addr333_2" type="text" style="width:60%;right:0%;float:right" onkeydown="triggerKeyPressOnNextSiblingFromWithinKeyPress(event)">
Itappears Here Too<input class="lineEditInput" id="addr333_3" type="text" style="width:60%;right:0%;float:right;" onkeydown="keyPressHandler(event)">
var gZeroEvent;
function keyPressRecorder(e)
  gZeroEvent = e;
function triggerKeyPressOnNextSiblingFromWithinKeyPress(TTT)
  if(typeof(gZeroEvent) != 'undefined')  {
function keyPressHandler(TTT)
  if(typeof(gZeroEvent) != 'undefined')  {
TTT.currentTarget.value+= gZeroEvent.key;

you can set the keyCode if you create your own event, you can copy existing parameters from any real keyboard event (ignoring targets since its the job of dispatchEvent) and :

ta = new KeyboardEvent('keypress',{ctrlKey:true,key:'Escape'})


I know the question asks for a javascript way of simulating a keypress. But for those who are looking for a jQuery way of doing things:

var e = jQuery.Event("keypress");
e.which = 13 //or e.keyCode = 13 that simulates an <ENTER>


The critical part of getting this to work is to realize that charCode, keyCode and which are all deprecated methods. Therefore if the code processing the key press event uses any of these three, then it’ll receive a bogus answer (e.g. a default of 0).

As long as you access the key press event with a non-deprecated method, such as key, you should be OK.

For completion, I’ve added the basic Javascript code for triggering the event:

const rightArrowKey = 39
const event = new KeyboardEvent('keydown',{'key':rightArrowKey})