How is document.createEvent supposed to work with key events?
Solution 1
Ok, when doing further testing, it seemed that when all key event parameters was properly initialised, then dispatchEvent worked without fireing an 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);
}
Solution 2
Keypress is an UIEvent
. You should use initUIEvent( 'type', bubbles, cancelable, windowObject, detail )
rather than initEvent()
. But for firefox, which implements a keyEvents
, you should create a KeyEvents
and initKeyEvents()
.
Ernelli
Updated on June 04, 2022Comments
-
Ernelli almost 2 years
I am trying to simulate keypresses in a web application, it is for an embedded system but it uses a Webkit derived browser. I have tested the code in Chrome and get the same error.
I tried to use code snippets from this example from Yahoo, but I keep getting the same error when firing the event using
dispatchEvent
. "target" is an 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 have tried
createEvent("Events")
as well and it always boils down to the same exception, both on the embedded system and in Chrome.