How should document.createEvent handle key events?

I'm trying to simulate keystrokes in a web application, it is for the embedded system, but uses a browser derived from Webkit. I checked the code in Chrome and got the same error.

I tried to use the code snippets from this example from Yahoo , but keep getting the same error when triggering an event using dispatchEvent . "target" is the HTML element in the DOM tree.

 function fireEvent(target) { var evt = document.createEvent("UIEvent"); evt.initEvent("keypress", true, true); target.dispatchEvent(evt); } 

It always throws:

"Error: UNSPECIFIED_EVENT_TYPE_ERR: DOM Events Exception 0"

I also tried createEvent("Events") , and it always comes down to the same exception, both in the embedded system and in Chrome.

+4
source share
3 answers

Well, during further testing, it seemed that when all the key parameters of the event were correctly initialized, dispatchEvent worked without exception.

The following code works.

 function fireEvent(target) { var evt = document.createEvent("Events"); evt.initEvent("keypress", true, true); evt.view = window; evt.altKey = false; evt.ctrlKey = false; evt.shiftKey = false; evt.metaKey = false; evt.keyCode = 0; evt.charCode = 'a'; target.dispatchEvent(evt); } 
+3
source

Keypress is UIEvent . You should use initUIEvent( 'type', bubbles, cancelable, windowObject, detail ) , not initEvent() . But for firefox that implements keyEvents , you have to create keyEvents and initKeyEvents() .

+2
source

This is an old thread, just to update it. I am adding another answer so that it makes sense to anyone.

initEvent () is deprecated. It is still supported in some browsers, but does not use it.

Better concise way to create such events

  function fireEvent(target) { var event = new Event('build'); // Listen for the event. target.addEventListener('build', function (e) { ... }, false); // Dispatch the event. target.dispatchEvent(event); } 

To add additional data to the event object, there is a CustomEvent interface, and the detail property can be used to transfer user data. For example, an event can be created as follows:

 var event = new CustomEvent('build', { 'detail': target.dataset.time }); 

Link: Creating and triggering events

0
source

All Articles