Running initKeyEvent only works in FireFox. need a cross browser solution!

This is my code:

<script>
function f(){
var i=document.getElementById("i");
i.focus();
 var evt = document.createEvent("KeyboardEvent");
    evt.initKeyEvent("keypress", true, true, null, false, false, false, false, 

0, 32);
    i.dispatchEvent(evt);
}
</script>
<body onload="f();">
<input id="i"/>
</body>

Open the script in firefox and it works. The empty space inside the input field indicates that the code worked.

However, the above code snippet does not work in Chrome, Safari, Opera, etc.

How can we modify the above code to work in these browsers?

+5
source share
2 answers

For Webkit-based browsers (Safari / Chrome), the event initialization call should look a bit different (see https://bugs.webkit.org/show_bug.cgi?id=13368 ):

initKeyboardEvent(in DOMString typeArg, 
                  in boolean canBubbleArg, 
                  in boolean cancelableArg, 
                  in views::AbstractView viewArg, 
                  in DOMString keyIdentifierArg, 
                  in unsigned long keyLocationArg, 
                  in boolean ctrlKeyArg, 
                  in boolean shiftKeyArg, 
                  in boolean altKeyArg, 
                  in boolean metaKeyArg, 
                  in boolean altGraphKeyArg);
+6
source

To add Alexander's answer:

webkit, , initKeyboardEvent, keyCode charCode 0: https://bugs.webkit.org/show_bug.cgi?id=16735

SO-.

+4

All Articles