Home > Web Front-end > JS Tutorial > body text

How to Simulate Keyboard Events in Safari Using JavaScript?

Patricia Arquette
Release: 2024-11-21 09:10:11
Original
634 people have browsed it

How to Simulate Keyboard Events in Safari Using JavaScript?

Simulating Keyboard Events in Safari Using JavaScript

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);
Copy after login

Approach 2:

var event = document.createEvent("UIEvents");
event.initUIEvent("keypress", true, true, window, 1);
event.keyCode = 115;
Copy after login

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})
Copy after login

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
});
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template