开发者

How is document.createEvent supposed to work with key events?

开发者 https://www.devze.com 2023-01-19 23:04 出处:网络
I am trying to simulate keypresses in a web app开发者_高级运维lication, 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 am trying to simulate keypresses in a web app开发者_高级运维lication, 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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号