0

Can someone help me with this code. I am trying to simulate a keyboard input for a web page without specifically specifying the control to send it to. I am trying to do so through createEvent and dispatchEvent. but when I receive the actual keypressed the event does not have any reference to the character. The charCode, keyCode and which are always 0.

Thanks for your help! Max

<html>
<body> 
    <button type="button" onclick="KeyPressInject('e')">TEST</button>
</body>

<script type="text/javascript">

addEventListener("keypress", function(event){ EventKeyPressed(event)}); 

function KeyPressInject(letter)
{
    var evt = document.createEvent("KeyboardEvent");
    Object.defineProperty(evt, 'keyCode', { 
                         get : function() {
                                 return this.keyCodeVal;
                         } });      
    evt.initKeyboardEvent ("keypress", true, false, window, false, false, false, false, letter, letter); 
    var canc = !window.dispatchEvent(evt);
}

function EventKeyPressed(event)
{
    console.log("Key Pressed " + event.charCode);
}   
</script>
</html>
user3396975
  • 1
  • 1
  • 1

1 Answers1

0

Please see if this helps, I've prepared a simple fiddle: Basically it triggers a keypress event

You give it the character and the element to fire:

simulateKeyPress("e", 'body');

It's different from your code that it needs to define the character pressed through the which property.

  • Thanks Mohammed, your help is appreciated. Would you know why my listener do receive the event? I see from fiddle that it goes through but still the listener does not seem to pick the event up. Again sorry if it seems trivial. I tried pretty much everything I could read about that and I dont seem to be able to make this work. – user3396975 Mar 08 '14 at 21:10
  • Please check if this helps: http://stackoverflow.com/questions/10455626/keydown-simulation-in-chrome-fires-normally-but-not-the-correct-key – Mohammed R. El-Khoudary Mar 08 '14 at 21:22