Vanilla JavaScript: Disabling a given preexisting key-combo in a webpage

半腔热情 提交于 2019-12-24 00:57:52

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/52924807/vanilla-javascript-disabling-a-given-preexisting-key-combo-in-a-webpage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!