Is it possible to simulate key press events programmatically?
Asked Answered
C

28

594

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

Clavier answered 27/2, 2009 at 20:17 Comment(2)
Can you clarify 'simulate'? Is your goal to test your website or is it to enact the onclick, onmousedown, etc functionality of a given link?Tahitian
Can you simulate "ctrl + d" to bookmark a page and bypass the current restriction?Lavena
T
245

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

var keyboardEvent = document.createEvent('KeyboardEvent');
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent';
    
keyboardEvent[initMethod](
  '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
);
document.dispatchEvent(keyboardEvent);
Timbuktu answered 29/8, 2012 at 22:18 Comment(12)
Philip, this looks like the code i need, but i need to dispatch the keypress event to a textarea. i tried to modify your code to send to a textarea, but it doesnt appear to work, in chrome at least, any idea what could be wrong? here is the jsfiddle that i have made to demonstrate: jsfiddle.net/szmJuStiver
Turns out there's a bug in Chromium with KeyboardEvent dispatching. Check out this thread for more details: #10456126.Timbuktu
keyCode is always 0, and I cannot change it.Tenement
This example doesn't work with initKeyboardEvent as the wrong parameters are given. See developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/…. The KeyboardEvent constructor should be used instead: developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/….Flummery
Note: the above link to KeyboardEvent.initKeyboardEvent() on MDN is wrong. Correct link: developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/…Pass
It appears that there's a bug in Chromium that causes the event.which to always be 0 when using document.createEvent("KeyboardEvent"). @lluft shared the details and a workaround, which worked for me, in this comment on a different thread. Basically, you need to use document.createEvent('Event') to create a generic event and then set the type to keydown and give a keyCode property equal to the key's charcode.Dredge
It seems that this feature has been removed by now. MDN has considered it deprecated for quite a while, though.Ecumenical
keyCode is 0 because it is deprecated. Use key instead. See my answer for more info https://mcmap.net/q/22213/-is-it-possible-to-simulate-key-press-events-programmaticallySmallscale
Is there any way this could be modified so that it can write inside input elements, because it doesn't seem to work for me.Lodged
It is not typing on textbox? How can I do this?Walkyrie
You could just use textAreaElement.value += "text";Marvelmarvella
Note that for security reasons there is no way to simulate key presses for many things, like trying to show the autocomplete list in an input linked to a datalist.Enchant
B
144

You can dispatch keyboard events on an EventTarget (element, Window, Document, others) like this:

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

However, dispatchEvent might not update the input field value, and it might not trigger behavior that a regular keyboard press does, likely because of the Event.isTrusted property, which I don't know if there's a way to get around

But you can also change an input by setting its value.

element.value += "a";

Example:

const element = document.querySelector('input');

element.addEventListener('keydown', e => console.log(e.key));
changeValButton.addEventListener('click', () => { element.value += "a"; });
dispatchButton.addEventListener('click', () => {
    const event = new KeyboardEvent('keydown', {'key': 'a'});

    element.dispatchEvent(event);
});
<input/>
<button id="dispatchButton">Press to dispatch event </button>
<button id="changeValButton">Press to change value </button>

You can add more properties to the event as needed, as in this answer. Take a look at the KeyboardEvent documentation

element.dispatchEvent(new KeyboardEvent("keydown", {
    key: "e",
    keyCode: 69, // example values.
    code: "KeyE", // put everything you need in this object.
    which: 69,
    shiftKey: false, // you don't need to include values
    ctrlKey: false,  // if you aren't going to use them.
    metaKey: false   // these are here for example's sake.
}));

Also, since keypress is deprecated you can use keydown + keyup, for example:

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

For pages with ReactJS, see: How to programmatically fill input elements built with React? on how to to simulate keyboard behavior.

Bundle answered 25/5, 2017 at 22:40 Comment(6)
I think that answer should mention the fact that dispatched in js event doesn't update input content.Accumulative
Latest Firefox isn't modern?Bearish
Seems that keypress is depreciated, using keydown instead -> developer.mozilla.org/en-US/docs/Web/Events/keypressDelrio
It works perfectly for me with Chrome Embedded, as I need.Parris
It is not filling the textbox, why?Walkyrie
@GörkemHacıoğlu I think like mentioned in the answer, isTrusted property is false.Solfa
B
82

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) {
    alert(e.which);
  });
  simulateKeyPress("e");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.1/jquery.min.js">
</script>
Balf answered 27/2, 2009 at 20:36 Comment(4)
Hi What I meant is: 1. Register a key event (letter e executes some JS) 2. From a other method I want to programatically press the letter e)Clavier
It does not work properly in Chrome, sorry. jQuery creates Event, but without important attributes - which, charCode, keyCode.Alcheringa
@Clavier This is not possible. See my answer for the reasoning behind it.Extensile
Note that trigger can't be used to mimic native browser events.Uranus
E
62

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:

jQuery('input[type=submit][name=btnK]')
  .trigger({
    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.

Disclosure: The answer is based on the answer here.

Extensile answered 9/11, 2013 at 22:20 Comment(3)
So with the JavaScript KeyboardEvent API (developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent) you can simulate key events, for example say that a key is pressed but it is not possible to have the key press effect, like writing characters 'a', 'b', 'c'? If it is possible, writing these basics characters is not a security problem but I understand that a special key like "F12" or a combination like "Alt+F4" should be forbidden.House
This is what I get when I run your jQuery in Chrome: Uncaught ReferenceError: character is not definedForgive
Disclosure Did you mean "Disclaimer"?Layette
S
47

As of 2019, this solution has worked for me:

document.dispatchEvent(
  new KeyboardEvent("keydown", {
    key: "e",
    keyCode: 69, // example values.
    code: "KeyE", // put everything you need in this object.
    which: 69,
    shiftKey: false, // you don't need to include values
    ctrlKey: false,  // if you aren't going to use them.
    metaKey: false   // these are here for example's sake.
  })
);

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

Clarification: This code dispatches a single keydown event, while a real key press would trigger one keydown event (or several of them if it is held longer), and then one keyup event when you release that key. If you need keyup events too, it is also possible to simulate keyup events by changing "keydown" to "keyup" in the code snippet.

This also sends the event to the entire webpage, hence the document. If you want only a specific element to receive the event, you can substitute document for the desired element.

Sailesh answered 30/11, 2019 at 4:20 Comment(4)
This is the only solution that worked for me in Qt QWebEngine runJavascript function. ThanksGeriatrics
completely ignored by Flash games for some reason (maybe Flash ignores everything that isn't Trusted ? )Kibbutznik
@Kibbutznik - To be honest, if you're using Flash in 2020, you really need to reconsider what tools are best suited for your purpose.Sailesh
Please let Flash dieCivilized
A
31

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
    alert("canceled");
  } 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().

Alcina answered 8/5, 2009 at 12:44 Comment(2)
Note: This is supported by Gecko browsers only.Keratoplasty
Gecko and other browsers disagreed on whether to use initKeyEvent or initKeyboardEvent(). Both are deprecated in favor of using the KeyboardEvent() constructor.Unipolar
C
28

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:

$('input').val('123');
$('input').change();
Chaconne answered 4/7, 2013 at 17:28 Comment(3)
I'm using Chrome. I'm running Javascript from the console. Your top line of code put's the text into the input box. But the .change() doesn't work. My site's input has an auto lookup where once you type 2 letters in the lookup function opens a drop-down with all the people in an organization whose last names start with those letters. Your code put's a name like "Smith" into the input box but it doesn't initiate the search dropdown to open for me. Your's is the cleanest code I see so far. What can I replace .change() with to make it work for me?Lactary
Got it... I sandwiched your .val code between aljgom's keydown and keyup lines. Works perfectly.Lactary
Worked great for me.Mathieu
P
18

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'}));
Prismoid answered 23/11, 2017 at 11:55 Comment(0)
P
16

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.


Edit: I'm not the original poster of this answer, but I have tested it and I can't get it to work for updating an input field. Here's a code snippet with the code for others to try or review

let element = document.querySelector('input');
element.onkeydown = e => console.log('keydown on element: ' +  e.key);
document.onkeydown = e => console.log('keydown on document: ' + e.key + " " + e.target);
dispatchButton.onclick = () => dispatchKey(element, 'a')

dispatchKey = (target, key) => {
    let dom = document;
    // focus (dispatched on the DOM with the target set)
        let ev = new Event('focus', {target: target});  
        // this part seems to not work? when logging the 
        // target in the onkeypress function it shows `document` instead of `input`
        // I also tried these and got the same behavior
        //    ev.target = target;
        // and 
        //    Object.defineProperty(ev, 'target', {writable: false, value: target});   
        dom.dispatchEvent(ev);
    // keydown (dispatched on the DOM)
        dom.dispatchEvent(new KeyboardEvent('keydown', {'key': key, target: target}));
    // beforeinput (dispatched at the target if it's a textarea or input)
        target.dispatchEvent(new Event('beforeinput'));
    // keypress (dispatched on the DOM)
        dom.dispatchEvent(new KeyboardEvent('keypress', {'key': key}));
    // input (dispatched at the target if it's a textarea or input)
        target.dispatchEvent(new Event('input'));
    // change (dispatched at the target if it's a select)

    // keyup (dispatched on the DOM)
        dom.dispatchEvent(new KeyboardEvent('keyup', {'key': key}));
    // Then, optionally for most:
    // blur (dispatched on the DOM with the target set)
        dom.dispatchEvent(new Event('blur', {target: target}));
    console.log('dispatched');
}
<input/>
<button id="dispatchButton">Press to dispatch events </button>
Pyrotechnics answered 30/5, 2014 at 22:40 Comment(8)
NDA for JavaScript? Really? , anyway for each character your algorithm is wrong, simulating "input" event anyway adds text without going through whole keydown,keyup event or any other event. Problem is how to handle multiple keypress events etc like pressing "a" button and expecting "aaaaaaa" multiple times.Electrodeposit
The trick is to fire a keydown, input, then keyup. If you want multiple "aaaaaa" keep firing the input event. and don't tell anyone.Pyrotechnics
I tried this out but it does not seem to work completely: I can trigger events for Enter, Backspace or arrow keys, but not with characters. For example, I cannot input text via this method although I followed your order of events closely.Ecumenical
@Ecumenical by chance you still have the code sample for triggering Enter according to this answer?Intra
I attempted this, no luck.Metrology
tried but didn't work for mocking Tab on the press of an enter... answer: https://mcmap.net/q/22213/-is-it-possible-to-simulate-key-press-events-programmaticallyGrizzled
This is not possible for security reasons: Manually firing an event does not generate the default action associated with that event. For example, manually firing a key event does not cause that letter to appear in a focused text input. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself. Source at MDN developer.mozilla.org/en-US/docs/Web/API/…Pioneer
The above snippet doesn't workNatale
F
15

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) {
    alert(String.fromCharCode(e.which));
    console.log(e);
  });
  // Simulate the key press
  $('body').simulateKeyPress('x');
});

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.

Forget answered 2/10, 2011 at 15:11 Comment(2)
SendKeys does NOT simulate keypresses it just injects values into the target elements.Granjon
Not simulating a hardware keypress, just calling binded keypress function.Sweptwing
O
8

just use CustomEvent

Node.prototype.fire=function(type,options){
     var event=new CustomEvent(type);
     for(var p in options){
         event[p]=options[p];
     }
     this.dispatchEvent(event);
}

4 ex want to simulate ctrl+z

window.addEventListener("keyup",function(ev){
     if(ev.ctrlKey && ev.keyCode === 90) console.log(ev); // or do smth
     })

 document.fire("keyup",{ctrlKey:true,keyCode:90,bubbles:true})
Oria answered 4/12, 2015 at 19:0 Comment(3)
I am trying your code. If I press a key I do get into the listener, but document.fire has no effect.Parachronism
"(" is not a problem. I fixed it right away. It's just not getting into it after document.fire. BTW, I am triggering it by clicking on an icon.Parachronism
My code is something like this: <img src="settings.svg" height="22" width="24" style="cursor: pointer;" ng-click="openAdminConsole()"> In openAdminConsole() I am doing document.fire. Is that not correct?Parachronism
G
8

I wanted to simulate a 'Tab' press... Expanding on Trevor's answer, we can see that a special key like 'tab' does get pressed but we don't see the actual result which a 'tab' press would have...

tried with dispatching these events for 'activeElement' as well as the global document object both - code for both added below;

snippet below:

var element = document.getElementById("firstInput");

document.addEventListener("keydown", function(event) {

  console.log('we got key:', event.key, '  keyCode:', event.keyCode, '  charCode:', event.charCode);

  /* enter is pressed */
  if (event.keyCode == 13) {
    console.log('enter pressed:', event);
    theKey = 'Tab';
    attributes = {
      bubbles: true,
      key: theKey,
      keyCode: 9,
      charCode: 0,
    };
    setTimeout(function() {
      /*  event.keyCode = 13;  event.target.value += 'b';  */
      var e = new window.KeyboardEvent('focus', attributes);
      document.activeElement.dispatchEvent(e);
      e = new window.KeyboardEvent('keydown', attributes);
      document.activeElement.dispatchEvent(e);
      e = new window.KeyboardEvent('beforeinput', attributes);
      document.activeElement.dispatchEvent(e);
      e = new window.KeyboardEvent('keypress', attributes);
      document.activeElement.dispatchEvent(e);
      e = new window.KeyboardEvent('input', attributes);
      document.activeElement.dispatchEvent(e);
      e = new window.KeyboardEvent('change', attributes);
      document.activeElement.dispatchEvent(e);
      e = new window.KeyboardEvent('keyup', attributes);
      document.activeElement.dispatchEvent(e);
    }, 4);

    setTimeout(function() {
      var e = new window.KeyboardEvent('focus', attributes);
      document.dispatchEvent(e);
      e = new window.KeyboardEvent('keydown', attributes);
      document.dispatchEvent(e);
      e = new window.KeyboardEvent('beforeinput', attributes);
      document.dispatchEvent(e);
      e = new window.KeyboardEvent('keypress', attributes);
      document.dispatchEvent(e);
      e = new window.KeyboardEvent('input', attributes);
      document.dispatchEvent(e);
      e = new window.KeyboardEvent('change', attributes);
      document.dispatchEvent(e);
      e = new window.KeyboardEvent('keyup', attributes);
      document.dispatchEvent(e);
    }, 100);



  } else if (event.keyCode != 0) {
    console.log('we got a non-enter press...: :', event.key, '  keyCode:', event.keyCode, '  charCode:', event.charCode);
  }

});
<h2>convert each enter to a tab in JavaScript... check console for output</h2>
<h3>we dispatchEvents on the activeElement... and the global element as well</h3>

<input type='text' id='firstInput' />
<input type='text' id='secondInput' />

<button type="button" onclick="document.getElementById('demo').innerHTML = Date()">
    Click me to display Date and Time.</button>
<p id="demo"></p>
Grizzled answered 17/3, 2020 at 23:13 Comment(0)
T
7

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

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;

$textBox.trigger(press);
Tenement answered 22/5, 2013 at 7:32 Comment(0)
H
5

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);
    }
    document.getElementById("MyTextArea").dispatchEvent(e);
    }
<input type="button" onclick="KeySimulation();" value=" Key Simulation " />
<textarea id="MyTextArea" rows="15" cols="30"></textarea>
Hon answered 13/3, 2017 at 2:33 Comment(1)
Be warned that initKeyboardEvent is deprecated. (Source)Molnar
S
5

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})
document.dispatchEvent(event)
Smallscale answered 12/8, 2019 at 17:26 Comment(1)
keyCode, not key now.Invercargill
T
4

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

I don't know where 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.

Triphylite answered 10/9, 2014 at 23:18 Comment(0)
B
4

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;
document.dispatchEvent(e);
Blackface answered 21/5, 2018 at 8:24 Comment(1)
Still works in a Safari and Chrome browserBlackface
C
4

you can simulate input password with this code:

tested on chrome 100% work

DoCustomEvent('password', '#loginpin');



function DoCustomEvent(ct, elem){
var key;
var pressEvent = document.createEvent("CustomEvent");
pressEvent.initCustomEvent("keypress", true, false);

for (var i =0; i < ct.length; ++i)
{
    key                     = ct.charCodeAt(i);
    pressEvent.bubbles      = true;
    pressEvent.cancelBubble = false;
    pressEvent.returnValue  = true;
    pressEvent.key          = ct.charAt(i);
    pressEvent.keyCode      = key;
    pressEvent.which        = key;
    pressEvent.charCode     = key;
    pressEvent.shiftKey     = false;
    pressEvent.ctrlKey      = false;
    pressEvent.metaKey      = false;

    document.querySelector(elem).focus();

    //keypress //beforeinput //input //sendkeys //select
    setTimeout(function() {
        var e = new window.KeyboardEvent('keypress', pressEvent);
        document.activeElement.dispatchEvent(e);
        e = new window.KeyboardEvent('input', pressEvent);
        document.activeElement.dispatchEvent(e);

    }, 0);

    document.querySelector(elem).value = document.querySelector(elem).value + ct.charAt(i);
}
Columbic answered 12/8, 2022 at 21:2 Comment(0)
C
3

yes the @aljgom and the @mike-sallese solution is the best and more simple and easy to use for me. It's possible to make something like :

<a id="LEFT" onclick="document.dispatchEvent(new KeyboardEvent('keydown', { keyCode: '37' }));"></a>

like this we don't care about the id or class, and we don't need put code inside somewhere else in the document.

Censurable answered 25/9, 2023 at 4:55 Comment(0)
A
2

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;
        document.dispatchEvent(e);
    }
    simulateKeydown(39, false, false, false);
Abessive answered 31/3, 2018 at 16:57 Comment(0)
Y
2

Native JavaScript with TypeScript supported solution:

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

Example

    const event = new KeyboardEvent("keydown", {
              keyCode: 38,
            } as KeyboardEventInit);
Yeah answered 15/7, 2019 at 22:14 Comment(0)
A
2

That's what I tried with js/typescript in chrome. Thanks to this answer for inspiration.

var x = document.querySelector('input');

var keyboardEvent = new KeyboardEvent("keypress", { bubbles: true });
// you can try charCode or keyCode but they are deprecated
Object.defineProperty(keyboardEvent, "key", {
  get() {
    return "Enter";
  },
});
x.dispatchEvent(keyboardEvent);

{
  // example
  document.querySelector('input').addEventListener("keypress", e => console.log("keypress", e.key))
  // unfortunatelly doesn't trigger submit
  document.querySelector('form').addEventListener("submit", e => {
    e.preventDefault();
    console.log("submit")
  })
}

var x = document.querySelector('input');

var keyboardEvent = new KeyboardEvent("keypress", { bubbles: true });
// you can try charCode or keyCode but they are deprecated
Object.defineProperty(keyboardEvent, "key", {
  get() {
    return "Enter";
  },
});
x.dispatchEvent(keyboardEvent);
<form>
  <input>
</form>
Arquebus answered 26/2, 2020 at 19:13 Comment(0)
M
1

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>
$("#element_id").trigger(e); 
Micrometeorology answered 11/3, 2019 at 13:30 Comment(0)
L
1

Building on @aljgom's answer:

This worked great for me. Instead of dispatching the event to an element like aljgom had suggested, just dispatch it to the document.

document.dispatchEvent(new KeyboardEvent("keydown", { key: "c" }));
Leucite answered 13/8, 2021 at 16:52 Comment(0)
R
1

Every few years I stumble upon this question and spend an hour of trial and error searching for an answer that works on Firefox. Sadly, I've yet to find one here. Maybe these answers worked at one point but don't anymore?

The only thing I have found that works is a library called bililiteRange. It has a function called sendkeys (note, it's all lowercase). sendkeys can type in an input and display those typed characters on the screen. Its API is also much more convenient/high level than KeyEvent (which is beside the point, since I've never been able to get KeyEvent working anyway). Here is an example showing how to use it:

const input = element.querySelector('.form-group.row .react-select__input');
bililiteRange(input).sendkeys('I typed this{enter}');

Unfortunately, the source code is a little bit too abstract for me to follow; I'm not sure what key difference it has that's lacking in all these other answers.

Suggesting a library is usually looked down upon, especially because external links can suddenly 404, but for what it's worth, I captured bililiteRange code on the wayback machine and made a non-expiring pastebin as a contingency.

I know this answer will save future me an hour+, and I suspect it will do the same for others.

Remodel answered 15/3, 2023 at 19:32 Comment(0)
K
0

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)">
<script>
var gZeroEvent;
function keyPressRecorder(e)
{
  gZeroEvent = e;
}
function triggerKeyPressOnNextSiblingFromWithinKeyPress(TTT)
{
  if(typeof(gZeroEvent) != 'undefined')  {
TTT.currentTarget.nextElementSibling.dispatchEvent(gZeroEvent);
keyPressHandler(TTT);
  }
}
function keyPressHandler(TTT)
{
  if(typeof(gZeroEvent) != 'undefined')  {
TTT.currentTarget.value+= gZeroEvent.key;
event.preventDefault();
event.stopPropagation();
  }
}
</script>

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'})
Keramics answered 25/3, 2018 at 6:55 Comment(0)
N
0

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, () => {})
document.dispatchEvent(event)
Neuberger answered 25/9, 2018 at 7:56 Comment(0)
B
-3

Best way to js full screen toggle method:

function toggleFullScreen() {
      if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen();
      } else if (document.exitFullscreen) {
        document.exitFullscreen();
      }
}
Buchholz answered 3/1, 2023 at 16:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.