Question

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 embeded system and in Chrome.

Was it helpful?

Solution

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);
}

OTHER TIPS

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().

This one is old thread, just to update it I am adding another answer so that it makes more sense to any one.

initEvent() is deprecated It is still supported in some browsers but avoid using it.

There is better concise way to create events like this

  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 more data to the event object, the CustomEvent interface exists and the detail property can be used to pass custom data. For example, the event could be created as follows:

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

Reference: Creating and Triggering Events

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top