Vanilla JS:完全禁用“保存”网页功能 [英] Vanilla JS: Totally disabling a "save" functionality in webpages

查看:68
本文介绍了Vanilla JS:完全禁用“保存”网页功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我是一名初级维基百科用户,只想尝试在编辑页面中使用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.

如果我去找一些希伯来语维基百科中的编辑页面我可以通过鼠标选中保存页面按钮来保存或发布页面(插图),我可以从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.key event.keyCode 不同,请参阅文档

  • e.key == 16&& e.key == 18&& e.key == 83 永远不会成真。

  • 从事件监听器返回 false t阻止事件传播。

  • 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. 如果事件监听器在捕获阶段注册,则无法阻止它运行。 (请阅读此处)的捕获和斑点阶段。

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

这篇关于Vanilla JS:完全禁用“保存”网页功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆