Javascript - simulate key events on Chrome 53
Asked Answered
G

1

4

I am trying to simulate key event (press) on Chrome 53. All the solutions that I found on StackOverflow seems not to be working..

My goal is to have a function that gets a keyCode and simulates a key press with it - Pure JS is required

function keyPressSimulate(keyCode) {...?}

Code samples that I already tried:

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

 document.fire("keyup",{ctrlKey:true,keyCode:90,bubbles:true})

Another one:

presskey:  function(k) {
                var e = new Event("keydown");
                e.keyCode= k;
                e.which=e.keyCode;
                e.altKey=false;
                e.ctrlKey=true;
                e.shiftKey=false;
                e.metaKey=false;
                document.dispatchEvent(e);
            }

And:

var e = new KeyboardEvent("keydown", {bubbles : true, cancelable : true, key : "Q", shiftKey : true});
global.document.dispatchEvent(e);

And:

presskey:  function(k) {
            var keyboardEvent = document.createEvent("KeyboardEvent");

            var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";


            keyboardEvent[initMethod](
                               "keydown",
                                true,      // bubbles oOooOOo0
                                true,      // cancelable
                                window,    // view
                                false,     // ctrlKeyArg
                                false,     // altKeyArg
                                false,     // shiftKeyArg
                                false,     // metaKeyArg
                                k,
                                0          // charCode
            );

            global.document.activeElement.dispatchEvent(keyboardEvent);
         }
Goofy answered 15/10, 2016 at 21:42 Comment(4)
I found many possible solutions here: #10456126 And none of them worked for meGoofy
The solution must be in pure jsGoofy
I don't mean to be rude, but I'm not sure anyone will help until you've shown more effort on your part...Stopwatch
adding code samples that I already triedGoofy
C
1

The keyCode property is deprecated and cannot be set while using the dedicated KeyboardEvent

However, you can use a custom event and set whatever property you want as a 2 step operation (it will be ignored if used in the constructor):

<div id="test" onkeydown="this.textContent = event.keyCode;"></div>
<button onclick="
    var e = new Event('keydown'); 
    e.keyCode = 42; 
    document.getElementById('test').dispatchEvent(e);
    ">click me</button>

Edit as per comments An event is triggered from a user interaction targeting a specific element in the document.

For instance, a user hitting a key on the keyboard is a succession of events (keydown, keyup, keypress). Some of those are captured by the browser to fill in the value of an input field, and then they are transmitted to Javascript as events. There are no feasible way to emulate a user hitting a key from within the Javascript sandbox except than to do it manually (1) detect where the focus is, (2) update the properties of the focussed element based on the default browser behavior, and then (3) trigger the appropriate events on the target element.

Cullie answered 15/10, 2016 at 22:41 Comment(10)
It looks like that I already tried it in my code examples. Maybe I am doing something wrong. Can you please provide a code example?Goofy
I edited my answer with a working example on Chrome 53.0Cullie
Did not worked for me. for example tried even on Google`s search page: var e = new Event('keydown'); e.keyCode = 42; document.getElementById('lst-ib').dispatchEvent(e); And nothing...Goofy
What did you expect it to do ? An Input field will not display the character based on the event. When doing the operation you mentioned, the event handler is triggered (line 11697 of the prettyfied javascript) as expected.Cullie
My whole issue is to trigger the event - for this result. I need to trigger an key press on an input (if character add it, if backspace delete...etc)Goofy
Then you should alter the value property of the input and then trigger the event. For Google example : var i = document.getElementById('lst-ib'); i.value = 'mysearch'; var e = new Event('keydown'); e.keyCode = 13; i.dispatchEvent(e); but you have to update the input value beforehandCullie
So your solution is just alter the value manualy by the keyCode? I need to detect if it is a character or delete or backspace or sace and alter the value by it? Sounds wrongGoofy
Yes, Events are a reaction to the input. If you want to simulate input, you should do it all by hand. So I suggest you rephrase your question or open a new one for that specific need.Cullie
I think the question ia very clearly. I have a keyCode and I want to simulate a press on keyboard with that keyCode the result will be the same as I will press the same key kn my keyboardGoofy
For changing some selected text a suggestion is to exec this document.execCommand('insertText', true, 'yourtext'); when the click happens, it also allows you to undo and redo (in webkit at least).Aeolian

© 2022 - 2024 — McMap. All rights reserved.