0

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);

})();
Piotr B
  • 1
  • 2
  • Does this answer your question? [Save HTML locally with Javascript](https://stackoverflow.com/questions/27177661/save-html-locally-with-javascript) – double-beep Mar 17 '23 at 13:36
  • Unfortunately not. I just want to send any key combination, e.g. CTRL+S is just an example – Piotr B Mar 17 '23 at 17:43

1 Answers1

0

I spent many hours looking and testing something that would work.

Finally, it worked.

The script sends the "down arrow" and "enter" key

In my question was CTRL+S , but I was just looking for an example....

function sendArrowDownKeyAndEnter() {
  // create a new arrow-down key event with additional fields
var arrowEvent = new KeyboardEvent("keydown", {
  key: "ArrowDown",
  keyCode: 40,
  code: "ArrowDown",
  which: 40,
  shiftKey: false,
  ctrlKey: false,
  altKey: false,
  metaKey: false
});

// create a new enter key event with additional fields
var enterEvent = new KeyboardEvent("keydown", {
  key: "Enter",
  keyCode: 13,
  code: "Enter",
  which: 13,
  shiftKey: false,
  ctrlKey: false,
  altKey: false,
  metaKey: false
});

// get the active element and dispatch the events to it
var activeElement = document.activeElement;
if (activeElement) {
  activeElement.dispatchEvent(arrowEvent);
  activeElement.dispatchEvent(enterEvent);
}

}
Piotr B
  • 1
  • 2