How to use the ctrl+s key combination correctly with tampermonkey ? The example code does not work correctly. The alert is displayed, but the key combination is not sent. Where is the error?
// ==UserScript==
// @name Ctrl+S button
// @NameSpace http://tampermonkey/ctrls
// @version 1
// @description Adds a button that saves the current page using Ctrl+S key combination in the browser window
// @MATCH *://*/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// create a button element
const button = document.createElement('button');
button.innerHTML = "File";
button.style.padding = "10px";
button.style.fontSize = "16px";
button.style.backgroundColor = "blue";
button.style.color = "white";
button.style.position = "fixed";
button.style.top = "100px";
button.style.left = "100px";
button.style.zIndex = "9999";
// define function to simulate key press
function simulateKeyPress(event) {
const saveEvent = new KeyboardEvent('keydown', {
key: 's',
ctrlKey: true
});
document.dispatchEvent(saveEvent);
alert("Press OK!");
}
// add event listener to button
button.addEventListener('click', simulateKeyPress);
// add button to the document body
document.body.appendChild(button);
})();