Vanilla JS:完全禁用“保存";网页中的功能

假设我是一名初级 Wikipedia 用户,只想尝试在编辑页面中使用 Wiki 文本编辑器更改一些 Wikipedian 内容,但不以任何方式保存我的更改(即使是错误的),因此寻求防止任何在编辑页面中保存功能的方法,通过 vanilla JavaScript.

Assume I'm a junior Wikipedia user that just want to experiment with changing some wikipedian content with the Wiki text editor in an edit-page, but not saving my changes in any way (not even by mistake), thus seeking a way to prevent any saving functionality in an edit-page, via vanilla JavaScript.

如果我去一些 edit-page 在希伯来语维基百科中我可以通过单击保存页面"按钮(插图)来保存或发布页面,其中我可以从 DOM 中删除:

If I go for some edit-page in Hebrew Wikipedia I can save or publish a page by mouse-clinking the Save page button (illustration), which I can remove from DOM with:

document.querySelector("#wpSave").remove();

<小时>

但假设我仍然可以通过 alt+shift+s 保存或发布内容,并且我也想防止这种可能的保存行为;我为此尝试了以下代码:


But let's assume I can still save or publish content by alt+shift+s and I'd like to prevent this possible saving behavior as well; I tried the following code for that:

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

代码失败(控制台中没有给出特殊错误).为什么失败了?

The code failed (no special error is given in console). Why it failed?

推荐答案

你的问题有很多问题:

  • event.keyevent.keyCode 不同,参考 文档.
  • e.key == 16 &&e.key == 18 &&e.key == 83 永远不会是真的.
  • 从事件侦听器返回 false 不会阻止事件传播.
  • event.key isn't the same as event.keyCode, Refer to the documentation.
  • e.key == 16 && e.key == 18 && e.key == 83 will never be true.
  • Returning false from an event listener doesn't stop the event from being propagated.

您正在尝试做的事情可以通过以下方式实现:

What you are trying to do can be achieved in the following way:

document.addEventListener("keypress", evt => {
  // refer to https://stackoverflow.com/a/2878005/8746648
  if(evt.altKey && evt.key == "S") {
    alert("prevent this message");
    evt.preventDefault();
  }
});

// refer to https://stackoverflow.com/a/35611393/8746648
document.addEventListener("keypress", evt => {
  if(evt.altKey && evt.key == "S") {
    evt.stopPropagation();
  }
}, true);

  1. 注意第二个事件监听器中的 true.
  2. 请注意,evt.key 与大写s"进行比较.
  3. 如果事件侦听器已在捕获阶段注册,则无法阻止它运行.(在这里了解捕获和blobbing阶段).
  1. Notice the true in the second event listener.
  2. Notice that evt.key is compared with an upper case "s".
  3. You can't prevent an event listener from running if it's registered in the capturing phase. (read about the capture and blobbing phases here).

相关文章