首页 > 解决方案 > 使用用户脚本删除元素

问题描述

第一次尝试用户脚本,尽管在互联网上找到了许多如何从页面中删除元素的示例,但它们都不起作用(这看起来也是用户脚本最基本的应用程序之一)。

在此页面上使用暴力猴子-2.12.8:

https://www.zerohedge.com/economics/2020-greatest-hits-most-popular-articles-past-year-and-look-ahead

我想删除“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); }

标签: userscripts

解决方案


根据帖子和评论,似乎元素是在 DOM 之后加载/创建的。在这种情况下,您需要在页面加载完成后运行脚本。

尽管在启用 JavaScript ( https://www.zerohedge.com/economics/2020-greatest-hits-most-popular-articles-past-year-and-look-ahead) 的链接上进行测试时,该元素不会出现,但这里有一个示例,说明如何删除该项目。可能还涉及其他因素(例如浏览器、国家/地区、登录、cookie 等)。

ViolentMonkey默认document-endDOM 加载之后但在所有外部元素加载之前运行。将用户脚本设置为在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 将其设置displaynone. 例如:

// ==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 在其运行时应用并且不会应用于稍后创建的元素(无需额外的方法使其再次运行)。


推荐阅读