Home > Web Front-end > JS Tutorial > How to Reliably Create Keyboard Events in Safari using JavaScript?

How to Reliably Create Keyboard Events in Safari using JavaScript?

Mary-Kate Olsen
Release: 2024-11-13 08:37:02
Original
935 people have browsed it

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

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

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!

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