Search code examples
javascriptgoogle-chrome-extensionfirefox-addon

How to remove elements in the content script before showing the page?


Here's my config:

  "content_scripts": [
    {
      "matches": ["https://www.baidu.com/"],
      "js": ["./baidu/baidu.js"]
    }
  ]

And here's my baidu.js

  // #region delete useless DOM
  const deleteIdList = [
    '#s_top_wrap',
    '#bottom_layer',
    '#lm-new',
    '#s-top-left',
    '#u1',
    '#s-hotsearch-wrapper',
    '#s_side_wrapper'
  ];
  deleteIdList.forEach(v => {
    const element = document.querySelector(v);
    element.style.display = 'none';
    // element.parentNode.removeChild(element);
  });

All I want is very simple, I just hope when I visit the baidu.com, the useless dom can be remove(or hide). My problem is as my config works, but the useless dom will flash in the beginning. Then those disappears. I hope when I see the web, everything's ok.

I've tried to specify the attribute run_at as document_start. Then my js file do not works.

How can I make it ? (Tested in FireFox browser)


Solution

  • "run_at": "document_start" in content script declaration is an absolute must for this.
    The content script will run when the page is empty so we also need one of the following:

    • observe the page being constructed by using MutationObserver on document, example, check the added nodes and hide those that match the list of ids.

    • or construct a style element with the selectors to hide.
      Performance-wise, it's orders of magnitude faster. Also simpler.

      hideSelectors([
        '#s_top_wrap',
        '#bottom_layer',
        '#lm-new',
        '#s-top-left',
        '#u1',
        '#s-hotsearch-wrapper',
        '#s_side_wrapper',
      ]);
      
      function hideSelectors(sels) {
        const el = document.createElement('style');
        el.textContent = sels.join(',') + '{ display: none !important }';
        // there's no <head> at this point so we're adding to <html>
        // which is allowed in DOM despite violating the HTML specification
        document.documentElement.appendChild(el);
      }