Tampermonkey script run before page load

后端 未结 1 896
我寻月下人不归
我寻月下人不归 2020-12-08 11:51

I need to hide a section from an html page:

相关标签:
1条回答
  • 2020-12-08 12:32

    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.

      • Modify elements immediately (not after page completely loads)?
      • How to change the HTML content as it's loading on the page ("rare elements" code)
      • Performance of MutationObserver to detect nodes in entire 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
      
    0 讨论(0)
提交回复
热议问题