Home >Web Front-end >JS Tutorial >How to Reliably Create Keyboard Events in Safari using JavaScript?
Creating Keyboard Events in Safari Using JavaScript
Simulating keyboard events in Safari using JavaScript can prove challenging, as demonstrated by your attempts to utilize document.createEvent. The issue stems from the inconsistent behavior of the keyCode property, which is initialized to 0 despite your efforts to set it to 115.
To address this, we recommend utilizing the DOM Keyboard Event Level 3 polyfill, which enhances JavaScript's event model to support modern browsers and provides backward compatibility for legacy properties.
With this polyfill, you can create keyboard events like so:
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})
The polyfill supports legacy properties like keyCode, charCode, and which, allowing you to specify these properties directly:
var e = new KeyboardEvent("keydown", { bubbles : true, cancelable : true, char : "Q", key : "q", shiftKey : true, keyCode : 81 });
Additionally, you can find a cross-browser version of initKeyboardEvent in a separate gist.
By utilizing these techniques, you can reliably create and dispatch keyboard events in Safari, ensuring consistent behavior across different browsers.
The above is the detailed content of How to Reliably Create Keyboard Events in Safari using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!