Home > Article > Web Front-end > How to Resolve Incorrect Key Input During Keydown Simulation in Chrome?
In a web application built using Chrome, simulating a keydown event on a textarea element can encounter challenges. Despite attempting to specify a specific keyCode, the textarea may receive an incorrect key value, such as the Enter key instead of the desired key.
To resolve this issue, you can employ a custom code that overrides both the 'keyCode' and 'which' properties in the 'KeyboardEvent' object. 'keyCode' is a legacy property that has been deprecated in favor of 'which'. Chrome behaves differently with these properties:
The following code provides an example of how to simulate a keydown event with the correct 'which' value in Chrome:
<code class="js">var keyEvent = document.createEvent('KeyboardEvent'); // Override 'keyCode' and 'which' properties Object.defineProperty(keyEvent, 'keyCode', { get: function() { return this.keyCodeVal; } }); Object.defineProperty(keyEvent, 'which', { get: function() { return this.keyCodeVal; } }); keyEvent.initKeyboardEvent('keydown', true, false, null, 0, false, 0, false, 77, 0); keyEvent.keyCodeVal = 77; inputNode.dispatchEvent(keyEvent);</code>
This code overrides the 'keyCode' and 'which' properties, ensuring that Chrome interprets the event correctly and triggers the desired key value (77) for the 'm' key.
The above is the detailed content of How to Resolve Incorrect Key Input During Keydown Simulation in Chrome?. For more information, please follow other related articles on the PHP Chinese website!