Vanilla JavaScript:在网页中禁用给定的预先存在的键组合

在这个随机的英语 – 维基百科编辑页面中,可以添加一些内容(比如“测试”),然后通过Alt + Shift + S的预先存在的键组合保存它。

我希望特别防止这种行为(不用document.querySelector("#wpSave").remove();保存按钮document.querySelector("#wpSave").remove(); )。

我尝试了以下失败的代码:

 // ==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; } }); }); 

我也尝试用e.preventDefault()evt.stopPropagation()替换return false ,但都失败了(没有控制台错误)。

代码有什么问题?


注意:这个问题与此问题的不同之处在于通常侧重于禁用给定的预先存在的键组合function,而不是一般地保存function


dotoconor的更新

我在控制台中使用了这个,但我仍然遇到同样的问题:

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

一次只能出现一个键事件,因此您必须创建一个状态机来确定哪些是打开和关闭的。 考虑一下:

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

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

现在有了这个,你可以检查你所需的键是否一次全部被按下,然后阻止最后一个按键向下滴下DOM。

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