Tampermonkey脚本在页面加载之前运行

Gio*_*lli 9 html javascript tampermonkey

我需要隐藏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>
Run Code Online (Sandbox Code Playgroud)

以下代码在Chrome dev中正常运行.工具

var ibmlogo = document.querySelectorAll('h1.logo.floatLeft');
ibmlogo[1].remove();
Run Code Online (Sandbox Code Playgroud)

但是当我在脚本处于活动状态时加载页面时,部分(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();
};
Run Code Online (Sandbox Code Playgroud)

有什么建议?谢谢Giovanni

wOx*_*xOm 21

需要:

现在有了上述选项,您可以:

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

    (document.head || document.documentElement).insertAdjacentHTML('beforeend',
        '<style>h1.logo.floatLeft { display: none!important; }</style>');
    
    Run Code Online (Sandbox Code Playgroud)
  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
    
    Run Code Online (Sandbox Code Playgroud)

  • 1. 这就是CSS表的用途。 2. 代码应该按原样工作,不要更改“observe”中的“document”参数。无论如何,我不是通灵者,所以我无法知道你的浏览器中发生了什么 (2认同)