【问题标题】:Tampermonkey script run before page loadTampermonkey 脚本在页面加载之前运行
【发布时间】:2017-01-13 18:40:18
【问题描述】:

我需要在 html 页面中隐藏一个部分:

<h1 data-ng-show="!menuPinned &amp;&amp; !isSaaS" class="logo floatLeft" aria-hidden="false"><span>XXX&nbsp;</span><span style="font-weight: bold;">XXX&nbsp;</span><span>XXXXX</span></h1>

以下代码在 Chrome 开发中运行良好。工具

var ibmlogo = document.querySelectorAll('h1.logo.floatLeft');
ibmlogo[1].remove();

但是当我加载页面并激活脚本时,部分 (h1) 不会消失。 我相信这是因为当脚本运行时,DOM 尚未完成加载,因此脚本无法找到选择器。

我尝试了许多不同的方法(例如 window.onLoad),但我的脚本仍然无效。最后一次尝试(失败)如下:

var logo = document.querySelectorAll('h1.logo.floatLeft');
logo.onload = function() {removeLogo()};

function removeLogo(){
    console.log("### logo array lenght: " + logo.length);
    logo[1].remove();
};

【问题讨论】:

  • 用户风格(例如使用Stylish)和h1.logo.floatLeft { display: none; } 会不会起到作用?

标签: javascript html tampermonkey


【解决方案1】:

必填:

  • @run-at: document-start 在用户脚本元块中。

    // ==UserScript==
    ..............
    // @run-at        document-start
    ..............
    // ==/UserScript==
    

现在有了以上选项,您的选择是:

  1. 只需注入隐藏徽标的样式:

    (document.head || document.documentElement).insertAdjacentHTML('beforeend',
        '<style>h1.logo.floatLeft { display: none!important; }</style>');
    
  2. 使用MutationObserver 检测并在元素添加到 DOM 后立即删除。

     

    new MutationObserver(function(mutations) {
        // check at least two H1 exist using the extremely fast getElementsByTagName
        // which is faster than enumerating all the added nodes in mutations
        if (document.getElementsByTagName('h1')[1]) {
            var ibmlogo = document.querySelectorAll('h1.logo.floatLeft')[1];
            if (ibmlogo) {
                ibmlogo.remove();
                this.disconnect(); // disconnect the observer
            }
        }
    }).observe(document, {childList: true, subtree: true});
    // the above observes added/removed nodes on all descendants recursively
    

【讨论】:

  • 感谢@woxxom,即使我不太明白怎么做,第一个选项也能解决问题。当脚本运行时我的元素不存在(我使用 document.querySelectorAll 进行了测试,那么 insertAdjacentHTML 如何在不存在的节点中注入一些东西?如果它创建一个节点,当页面最终加载时,它不应该覆盖我的注入元素?
  • 嗨,他无法让他的第二个选项(更漂亮)工作,在你的代码中,我在倒数第二行出现语法错误(不明白为什么)。然后我尝试了来自 mozilla 网站的示例,代码失败,因为目标不是节点,并检查它,当我创建目标时,元素不存在(我什至尝试使用 'html')并且目标始终为空. .干杯
  • 1.这就是 CSS 表 2 的用途。代码应该按原样工作,不要更改 observe 中的 document 参数。反正我不是通灵者,所以我不知道你的浏览器会发生什么
猜你喜欢
  • 2021-05-26
  • 2018-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-03
  • 2022-10-07
  • 1970-01-01
相关资源
最近更新 更多