Se si vuole farlo nel modo giusto, si può utilizzare DOM Keyboard Event Level 4 KeyboardEvent construct e chiave proprietà.
In browser più recenti o con DOM Keyboard Event Level 3/4 polyfill si può fare qualcosa di simile:
element.addEventListener(function(e){ console.log(e.key, e.char, e.keyCode) })
var e = new KeyboardEvent("keydown", {bubbles : true, cancelable : true, key : "Q", char : "Q", shiftKey : true});
element.dispatchEvent(e);
//If you need legacy property "keyCode".
// Note: In some browsers you can't overwrite "keyCode" property. (At least in Safari)
delete e.keyCode;
Object.defineProperty(e, "keyCode", {"value" : 666})
Example
"map event.key to character values of a normal QUERTY (en-US) layout" proposal demo
Nota che keyCode e charCode sono obsoleti in ultima Spec (www .w3.org/TR/DOM-Level-3-Events /). Pertanto, Chrome non ha alcuna possibilità di implementare initKeyEvent con il supporto keyCode. Ma si può sempre ignorare questo valore: UPDATE: cattivo metodo:
var evt = document.createEvent('KeyboardEvent');
evt.initKeyEvent("keypress", false, true, null, false, false,
shift, false, keyCode(key), key.charCodeAt(0));
if(evt.keyCode != keyCode(key)) {
delete evt.keyCode;
// Note: In some browsers you can't overwrite "keyCode" property. (At least in Safari)
Object.defineProperty(evt, "keyCode", { keyCode(key) });
}
Oppure si può aggiornamento prototipo evento: UPDATE: cattivo metodo:
// Note: In some browsers you can't overwrite "keyCode" property. (At least in Safari)
var _native_keyCode_getter = Object.getOwnPropertyDescriptor(KeyboardEvent.prototype, "keyCode");
Object.defineProperty(KeyboardEvent.prototype, "keyCode", {
"enumerable" : true,
"configurable" : true,
"get" : function() {
if("__keyCode" in this)return this["__keyCode"];
return _native_keyCode_getter.call(this);
},
"set" : function(newValue) {
return this["__keyCode"] = isNaN(newValue) ? 0 : newValue;
}
});
Aggiornamento Esistono varie implementazioni di initKeyboardEvent.Nel mio polyfill KeyboardEvent rilevo in qualche modo simile a questo (gist):
var _initKeyboardEvent_type = (function(e) {
try {
e.initKeyboardEvent(
"keyup" // in DOMString typeArg
, false // in boolean canBubbleArg
, false // in boolean cancelableArg
, global // in views::AbstractView viewArg
, "+" // [test]in DOMString keyIdentifierArg | webkit event.keyIdentifier | IE9 event.key
, 3 // [test]in unsigned long keyLocationArg | webkit event.keyIdentifier | IE9 event.location
, true // [test]in boolean ctrlKeyArg | webkit event.shiftKey | old webkit event.ctrlKey | IE9 event.modifiersList
, false // [test]shift | alt
, true // [test]shift | alt
, false // meta
, false // altGraphKey
);
return ((e["keyIdentifier"] || e["key"]) == "+" && (e["keyLocation"] || e["location"]) == 3) && (
e.ctrlKey ?
e.altKey ? // webkit
1
:
3
:
e.shiftKey ?
2 // webkit
:
4 // IE9
) || 9 // FireFox|w3c
;
}
catch (__e__) { alert("browser do not support KeyboardEvent") }
})(document.createEvent("KeyboardEvent"));
var e = document.createEvent("KeyboardEvent");
...
if("initKeyEvent" in e) {//FF
//https://developer.mozilla.org/en/DOM/event.initKeyEvent
e.initKeyEvent(type, _bubbles, _cancelable, _view, _ctrlKey, _altKey, _shiftKey, _metaKey, _keyCode, _keyCode);
}
else if("initKeyboardEvent" in e) {//https://developer.mozilla.org/en/DOM/KeyboardEvent#initKeyboardEvent()
if(_try_initKeyboardEvent) {
if(_initKeyboardEvent_type == 1) { // webkit
//http://stackoverflow.com/a/8490774/1437207
//https://bugs.webkit.org/show_bug.cgi?id=13368
e.initKeyboardEvent(type, _bubbles, _cancelable, _view, _key, _location, _ctrlKey, _shiftKey, _altKey, _metaKey, _altGraphKey);
}
else if(_initKeyboardEvent_type == 2) { // old webkit
//http://code.google.com/p/chromium/issues/detail?id=52408
e.initKeyboardEvent(type, _bubbles, _cancelable, _view, _ctrlKey, _altKey, _shiftKey, _metaKey, _keyCode, _keyCode);
}
else if(_initKeyboardEvent_type == 3) { // webkit
e.initKeyboardEvent(type, _bubbles, _cancelable, _view, _key, _location, _ctrlKey, _altKey, _shiftKey, _metaKey, _altGraphKey);
}
else if(_initKeyboardEvent_type == 4) { // IE9
//http://msdn.microsoft.com/en-us/library/ie/ff975297(v=vs.85).aspx
e.initKeyboardEvent(type, _bubbles, _cancelable, _view, _key, _location, _modifiersListArg, _repeat, _locale);
}
else { // FireFox|w3c
//http://www.w3.org/TR/DOM-Level-3-Events/#events-KeyboardEvent-initKeyboardEvent
//https://developer.mozilla.org/en/DOM/KeyboardEvent#initKeyboardEvent()
e.initKeyboardEvent(type, _bubbles, _cancelable, _view, _char, _key, _location, _modifiersListArg, _repeat, _locale);
}
}
}
ho rimosso un commento dalla questione e mettere come risposta, perché penso che anche pensato che non risolve veramente il problema, potrebbe essere molto utile per le persone che hanno lo stesso problema come ho fatto io. – fserb
Ehi, come hai risolto il problema? Sto anche affrontando il problema di simulare la pressione dei tasti di sinistra e destra su chrome/safari. Ma nessun successo, come hai fatto? – MaX
Hai provato la soluzione che ho postato? Ha funzionato per me e probabilmente ti avrebbe aiutato a raggiungere il tuo obiettivo, quindi è strano per me che tu abbia accettato la tua risposta di "è un bug". – Dennis