Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initKeyEvent keypress 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's working. The empty space within the input box shows that the code has worked.

However the above piece of code doesn't work in Chrome, Safari, Opera etc etc.

How do we modify the code above to make it work in these browsers?

like image 571
Pacerier Avatar asked Jun 20 '11 04:06

Pacerier


2 Answers

For Webkit-based browsers (Safari/Chrome), the event initialization call should look a bit differently (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);
like image 183
Alexander Pavlov Avatar answered Nov 02 '22 15:11

Alexander Pavlov


To add to Alexander's response:

There is a webkit bug that keyboard events initialized using initKeyboardEvent get an incorrect keyCode and charCode of 0: https://bugs.webkit.org/show_bug.cgi?id=16735

A working solution for this is posted in this SO answer.

like image 20
tanushree Avatar answered Nov 02 '22 15:11

tanushree