Home >Web Front-end >JS Tutorial >How to Simulate Keyboard Events in Safari with Accurate Key Code Propagation?
When attempting to simulate keyboard events in Safari using conventional approaches, developers often encounter issues with key codes being set to zero instead of the desired value. However, there is a reliable solution available using JavaScript's DOM Keyboard Event Level 3 polyfill.
The DOM Keyboard Event Level 3 polyfill empowers developers to create and dispatch keyboard events with enhanced compatibility. To use this polyfill, follow these steps:
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 require legacy properties such as "keyCode," "charCode," and "which," the updated polyfill fully supports them. Simply initialize the KeyboardEvent as follows:
var e = new KeyboardEvent("keydown", { bubbles : true, cancelable : true, char : "Q", key : "q", shiftKey : true, keyCode : 81 });
For cross-browser compatibility, consider using the following alternative initKeyboardEvent method:
function initKeyboardEvent(type, bubbles, cancelable, view, key, location, modifiersList, repeat, locale) { var evt = document.createEvent("KeyboardEvent"); evt.initKeyboardEvent(type, bubbles, cancelable, view, key, location, modifiersList, repeat, locale); return evt; }
By leveraging the DOM Keyboard Event Level 3 polyfill or the alternative initKeyboardEvent method, you can now reliably create and dispatch keyboard events in Safari, ensuring accurate key code propagation.
The above is the detailed content of How to Simulate Keyboard Events in Safari with Accurate Key Code Propagation?. For more information, please follow other related articles on the PHP Chinese website!