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);
         }
Oz Bar-Shalom
  • 1,747
  • 1
  • 18
  • 33

1 Answers1

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.

Simon
  • 2,353
  • 1
  • 13
  • 28
  • 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? – Oz Bar-Shalom Oct 15 '16 at 22:43
  • I edited my answer with a working example on Chrome 53.0 – Simon Oct 15 '16 at 23:17
  • 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... – Oz Bar-Shalom Oct 15 '16 at 23:27
  • 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. – Simon Oct 15 '16 at 23:39
  • 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) – Oz Bar-Shalom Oct 15 '16 at 23:41
  • 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` beforehand – Simon Oct 15 '16 at 23:45
  • 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 wrong – Oz Bar-Shalom Oct 15 '16 at 23:48
  • 1
    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. – Simon Oct 15 '16 at 23:50
  • 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 keyboard – Oz Bar-Shalom Oct 15 '16 at 23:52
  • 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). – Timo Huovinen Apr 20 '17 at 13:19