Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
749 views
in Technique[技术] by (71.8m points)

javascript - Tampermonkey script run before page load

I need to hide a section from an html page:

<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>

The following code works fine in Chrome dev. tools

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

But when I load the page with the script active, the section (h1) won't disappear. I believe this is because when the script runs, the DOM has not been completed loaded yet, hence the script fails to find the selector.

I have tried many different things (e.g. window.onLoad) but still my script is not effective. Last attempt (failed) is the following:

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

function removeLogo(){
    console.log("### logo array lenght: " + logo.length);
    logo[1].remove();
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Required:

  • @run-at: document-start in userscript metablock.

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

Now with the above your options are:

  1. Simply inject a style that hides the logo:

    (document.head || document.documentElement).insertAdjacentHTML('beforeend',
        '<style>h1.logo.floatLeft { display: none!important; }</style>');
    
  2. Use MutationObserver to detect and delete the element immediately after it's added into 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
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...