In an attempt to simulate keyboard events within the Safari browser, two approaches were tested using JavaScript:
Approach 1:
var event = document.createEvent("KeyboardEvent"); event.initKeyboardEvent("keypress", true, true, null, false, false, false, false, 115, 0);
Approach 2:
var event = document.createEvent("UIEvents"); event.initUIEvent("keypress", true, true, window, 1); event.keyCode = 115;
However, after executing either code, the event object's keyCode/which properties remained set to 0, indicating an unsuccessful simulation.
Solution:
According to the DOM Keyboard Event Level 3 polyfill, the following approach can be employed:
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 the legacy "keyCode" property is required: delete e.keyCode; Object.defineProperty(e, "keyCode", {"value" : 666})
Additional Updates:
The DOM Keyboard Event Level 3 polyfill now supports legacy properties:
var e = new KeyboardEvent("keydown", { bubbles : true, cancelable : true, char : "Q", key : "q", shiftKey : true, keyCode : 81 });
For cross-browser compatibility, the following initKeyboardEvent function can be utilized outside of the polyfill:
function initKeyboardEvent(type, bubbles, cancelable, view, key, location, modifiers, repeat) { var event = document.createEvent("KeyboardEvent"); event.initKeyboardEvent(type, bubbles, cancelable, view, key, location, modifiers, repeat, false, false, false, false, false, false, 0); return event; }
Refer to the provided examples and demo for further illustration.
The above is the detailed content of How to Simulate Keyboard Events in Safari Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!