使用 tampermonkey 阻止网站上的 2 个内容

问题描述 投票:0回答:1

我想用 tampermonkey 阻止网站 (www.exemple.com) 上的 2 个内容:

  • 网站上的所有 iframe
  • div id="dodo"

我已经尝试过这个(到 Id="dodo"),但它不起作用 :

// ==UserScript==
// @name         Kill dodo
// @namespace    http://tampermonkey.net/
// @match        https://www.exemple*
// @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// @grant    GM.getValue

// ==/UserScript==
//- The @grant directives are needed to restore the proper sandbox.
/* global $, waitForKeyElements */

waitForKeyElements ("[id='dodo']", killNode);

function killNode (jNode) {
    jNode.remove ();
}

对于 iframe 我不知道。 感谢您的帮助,并为我的英语不好而抱歉!

iframe tampermonkey
1个回答
0
投票

网页设计的一个基本规则是,任何页面上不能有多个具有相同 ID 的元素。 ID 在页面上应该是唯一的。现代网页设计不尊重这一点,您现在必须为此做好计划。

同样,现代网页可能很复杂,在组件中呈现,现在通常需要非常具体地使用 document.querySelector / documentGetElementBy... 函数中使用的 CSS 选择器。需要对 DOM 遍历有很好的理解。请参阅本答案末尾的注释 B 和 C。

此外,在我们的现代时代,元素会在不同的时间添加到页面中 - 即使在初始页面加载期间,在 document.ready / DOMContentLoaded 事件触发后,也可能会存在 ajax 查询和其他项目添加到页面中。再次强调,只需为此做好计划(通过在猎人/杀手代码之前添加等待代码)。

尝试这样的事情:

// ==UserScript==
// @name         Kill dodo
// @namespace    http://tampermonkey.net/
// @match        https://www.example*
// @grant        none

(async function() {
    'use strict';
    const $ = document.querySelector.bind(document);
    let repeatF=0, maxrepeats=100;

    kill_the_dodo();
    kill_all_iframes();

    function kill_the_dodo(){
        //THIS selector might need to become more specific (See notes B, C)
        while ( !$('#dodo') ){
            await sleep(100);
        }
        await sleep(100);
        $('#dodo').remove();
        //Assuming only one #dodo element, no need to repeat
    };

    function kill_all_iframes(){
        //THIS selector might need to become more specific
        while ( !$('iframe') ){
            await sleep(100);
        }
        await sleep(100);
        $('iframe').remove();
        //OPTIONAL: repeat 100x
        repeatF++;
        if (repeatF < 100) setTimeout( () => {kill_all_iframes()},250);
    };
})();

function sleep(ms){
    return new Promise(function (resolve, reject) {
        setTimeout(()=>{
            resolve();
        },ms);
    })
}

备注:

(a) 上面的代码是普通的 javascript,而不是 jQuery

(b) 在构建 CSS 选择器时使用控制台 (F12) 进行试验,以深入找到要删除的所需元素(例如 >

document.querySelector(' insert your CSS selectors one by one here ');

(c) 这是一个视频,它将帮助您了解如何深入浏览 DOM 以查找特定元素

© www.soinside.com 2019 - 2024. All rights reserved.