How to Dispatch a Keyboard Event in Safari Using JavaScript
In JavaScript, simulating keyboard events can prove problematic, especially in Safari. This issue arises when you attempt to set specific keyCode or which properties within your event object. Instead, these properties default to 0, hindering the seamless execution of your event simulation logic.
To address this issue, a reliable solution involves utilizing the DOM Keyboard Event Level 3 polyfill. By implementing this polyfill, you can leverage an enhanced syntax that allows you to define the key, char, and shiftKey properties directly. Additionally, it supports the definition of legacy properties like "keyCode," "charCode," and "which," offering compatibility with older browsers:
element.addEventListener("keydown", 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})
By leveraging the polyfill, you can now effectively dispatch keyboard events with the desired keyCode values, ensuring reliable event simulation in Safari.
The above is the detailed content of How to Simulate Keyboard Events in Safari with the Correct Keycode?. For more information, please follow other related articles on the PHP Chinese website!