2

In this random English-Wikipedia edit page one can add some content (say "test"), then saving it by the preexisting key-combo of Alt+Shift+S.

I desire to prevent this behavior specifically (without removing the save button with document.querySelector("#wpSave").remove();).

I tried the following code that failed:

// ==UserScript==
// @name         wiki
// @match        https://*.wikipedia.org/*
// ==/UserScript==

document.addEventListener("DOMContentLoaded", ()=>{
    document.addEventListener('keypress', function(e) {
        if (e.key == 16 && e.key == 18 && e.key == 83) {
            return false;
        }
    });
});

I also tried replacing return false with e.preventDefault() or evt.stopPropagation(), but all failed (no console errors).

What's wrong with the code?


Note: This question differs from this one by focusing on disabling a given preexisting key-combo functionality in general, and not on saving functionalities in general.


Update for dotoconor

I used this in console but I still have the same problem:

document.addEventListener("DOMContentLoaded", ()=>{
    const state = {};
    document.addEventListener('keydown', function(e) {
        state[e.key] = true;
    });

    document.addEventListener('keyup', function(e) {
        state[e.key] = false;
    });

    document.addEventListener('keyup', function(e) {
        state[e.key] = false;
        if (state["Alt"] && state["Shift"] && (state["S"] || state["s"])) {
            return e.preventDefault();
        }
    });
});
Osi
  • 1
  • 3
  • 9
  • 30
  • 1
    Possible duplicate of [Overriding Browser's Keyboard Shortcuts](https://stackoverflow.com/questions/3680919/overriding-browsers-keyboard-shortcuts) – Maor Refaeli Oct 22 '18 at 08:12
  • [The values of `key` property](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) would be good to know ... And how [keypress](https://developer.mozilla.org/en-US/docs/Web/Events/keypress) actually works. – Teemu Oct 22 '18 at 08:13

1 Answers1

0

Only one key event will be present at a time, so you have to create a state machine to determine which ones are on and off. Consider this:

const state = {};
document.addEventListener('keydown', function(e) {
  state[e.key] = true;
});


document.addEventListener('keyup', function(e) {
  state[e.key] = false;
});

Now with this, you can check if your desired keys are all being pushed down at one time, then prevent the last keypress from trickling down the DOM.

document.addEventListener('keyup', function(e) {
  state[e.key] = false;
  if (state["Alt"] && state["Shift"] && (state["S"] || state["s"])) {
    return e.preventDefault();
  }
});
dotconnor
  • 1,736
  • 11
  • 22