userscripts - 使用用户脚本删除元素
问题描述
第一次尝试用户脚本,尽管在互联网上找到了许多如何从页面中删除元素的示例,但它们都不起作用(这看起来也是用户脚本最基本的应用程序之一)。
在此页面上使用暴力猴子-2.12.8:
我想删除“exitModalOverlay” div(在开发人员工具中禁用它正是我想要的),这会使页面变黑(阻止我阅读它)。
我将插入我发现的一种更常见的技术(它不起作用)。我将不胜感激任何方法。谢谢。
// ==UserScript==
// @namespace confused
// @name zehohedge_remove_subscription_popup
// @version 1
// @description removes the overlay div that asks to subscribe
// @match https://www.zerohedge.com/*
// @grant none
// @noframes
// ==/UserScript==
var todelete = document.getElementById('exitModalOverlay');
if (todelete) { todelete.parentNode.removeChild(todelete); }
解决方案
根据帖子和评论,似乎元素是在 DOM 之后加载/创建的。在这种情况下,您需要在页面加载完成后运行脚本。
尽管在启用 JavaScript ( https://www.zerohedge.com/economics/2020-greatest-hits-most-popular-articles-past-year-and-look-ahead
) 的链接上进行测试时,该元素不会出现,但这里有一个示例,说明如何删除该项目。可能还涉及其他因素(例如浏览器、国家/地区、登录、cookie 等)。
ViolentMonkey默认在document-end
DOM 加载之后但在所有外部元素加载之前运行。将用户脚本设置为在document-idle
加载所有内容后将运行。
// ==UserScript==
// @namespace confused
// @name zehohedge_remove_subscription_popup
// @version 1
// @description removes the overlay div that asks to subscribe
// @match https://www.zerohedge.com/*
// @grant none
// @noframes
// @run-at document-idle
// ==/UserScript==
// find element
const todelete = document.getElementById('exitModalOverlay');
// remove element if found
if (todelete) { todelete.remove(); }
删除元素并不是摆脱元素的唯一方法。您还可以使用 CSS 将其设置display
为none
. 例如:
// ==UserScript==
// @namespace confused
// @name zehohedge_remove_subscription_popup
// @version 1
// @description removes the overlay div that asks to subscribe
// @match https://www.zerohedge.com/*
// @grant GM_addStyle
// @noframes
// ==/UserScript==
const css = `
#exitModalOverlay {
display: none;
}`;
GM_addStyle(css);
使用 JavaScript 将 CSS 应用到元素上GM_addStyle
(虽然不如上面)
// ==UserScript==
// @namespace confused
// @name zehohedge_remove_subscription_popup
// @version 1
// @description removes the overlay div that asks to subscribe
// @match https://www.zerohedge.com/*
// @grant none
// @noframes
// @run-at document-idle
// ==/UserScript==
// find element
const todelete = document.getElementById('exitModalOverlay');
// remove element if found
if (todelete) { todelete.style.display = 'none'; }
值得注意的是,CSS 始终适用(除非特别重写),即使元素是稍后创建的,而 JavaScript 在其运行时应用并且不会应用于稍后创建的元素(无需额外的方法使其再次运行)。
推荐阅读
- git - Git 状态显示 git reset 后的更改——hard, 2nd checkout——删除更改
- oracle - Oracle 自动在多记录块中插入记录第 2 部分
- php - 如何将变量附加到魔术方法PHP?
- ruby-on-rails - 如何使用 Bootstrap 警报自定义设计的确认消息?
- java - 将整数格式化为 %d 和 %s 有什么区别?
- hadoop-yarn - 当 flink 作业失败时,纱线将 flink 作业报告为 FINISHED 和 SUCCEED
- javascript - Dynamics CRM 表单的客户端大小操作
- facebook - 使用 GraphQL API 获取有关在 Facebook 上发帖的信息
- angular - Angular 6:调用订阅方法时视图未更新
- c# - 区分来自 2 个独立键盘的输入