Simulating keydown events on a textarea in Chrome using initKeyboardEvent results in the wrong key being typed. Setting keyCode explicitly fails to resolve the issue.
The key to successfully simulating keydown events lies in overriding not only the keyCode property but also the which property, as demonstrated below:
<code class="js">document.addEventListener('keydown', e => console.log( 'altKey : ' + e.altKey + '\n' + 'charCode (Deprecated) : ' + e.charCode + '\n' + 'code : ' + e.code + '\n' + 'ctrlKey : ' + e.ctrlKey + '\n' + 'isComposing : ' + e.isComposing + '\n' + 'key : ' + e.key + '\n' + 'keyCode (Deprecated) : ' + e.keyCode + '\n' + 'location : ' + e.location + '\n' + 'metaKey : ' + e.metaKey + '\n' + 'repeat : ' + e.repeat + '\n' + 'shiftKey : ' + e.shiftKey + '\n' + 'which (Deprecated) : ' + e.which + '\n' + 'isTrusted : ' + e.isTrusted + '\n' + 'type : ' + e.type )); Podium = {}; Podium.keydown = function(k) { var oEvent = document.createEvent('KeyboardEvent'); // Chromium Hack Object.defineProperty( oEvent, 'keyCode', { get : function() { return this.keyCodeVal; } } ); Object.defineProperty( oEvent, 'which', { get : function() { return this.keyCodeVal; } } ); if (oEvent.initKeyboardEvent) { oEvent.initKeyboardEvent("keydown", true, true, document.defaultView, false, false, false, false, k, k); } else { oEvent.initKeyEvent("keydown", true, true, document.defaultView, false, false, false, false, k, 0); } oEvent.keyCodeVal = k; if (oEvent.keyCode !== k) { alert("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")"); } document.dispatchEvent(oEvent); } //Sample usage Podium.keydown(65);</code>
The above is the detailed content of How to Correctly Simulate Keydown Events in Chrome?. For more information, please follow other related articles on the PHP Chinese website!