views:

18

answers:

1

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

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.

EDIT

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