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

时间:2016-09-06 10:27:31

标签: javascript html 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>

以下代码在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();
};

有什么建议吗?谢谢Giovanni

1 个答案:

答案 0 :(得分:16)

<强>必需:

    用户脚式元区块中的
  • @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
    
相关问题