How to insert/replace a specific CSS when a website loads

Viewed 636

When you open YouTube they give you a whole bunch of videos they "Recommend" to you, or which are "Trending", these videos are just random but often times they are also very political. I don't want to see that sort of stuff.

I'd like to have a clean YouTube-Page with just the searchbar and nothing else and I had hoped there was some sort of method with which I could inject a custom CSS snipped when loading the YouTube Home Page, which would get rid of the entire section for me.

I've pinpointed the issue to this header here:

<ytd-rich-grid-renderer 
    class="style-scope ytd-two-column-browse-results-renderer" 
    style="--ytd-rich-grid-items-per-row:3; 
           --ytd-rich-grid-posts-per-row:3; 
           --ytd-rich-grid-movies-per-row:5;" 
    mini-mode="">

    <!-- here is where all the recommended and trending stuff is -->

</ytd-rich-grid-renderer>

The only thing I'd like to do automatically when the page loads is to remove every class and style from this div and replace it with style="display:none" instead, so it would look like this:

<ytd-rich-grid-renderer style="display:none">

    <!-- now all recommended and trending stuff as been rendered invisible -->

</ytd-rich-grid-renderer>

This works without a problem but as I said, I'd like to have this happen automatically when the page loads and I'm not sure how this can be done or if it is even possible.

If it is possible then I'd like to know how it could be achieved (maybe using cookies, or something like that). I'm using Google Chrome as browser and I'm only using the Incognito Mode.

1 Answers

One way to do this is with a userscript. Install a userscript manager like Tampermonkey and append a <style> tag to the document when on youtube.

Identify the CSS selectors of the elements you want to hide, and give them display: none:

// ==UserScript==
// @name         Hide Youtube Junk
// @match        https://www.youtube.com/*
// @grant        none
// ==/UserScript==

document.body.appendChild(document.createElement('style')).textContent = `
ytd-two-column-browse-results-renderer, [id="masthead-ad"] {
  display: none !important;
}
`;

To run a usescript as soon as possible, so that the elements don't appear for a moment before the page loads, use @run-at document-start, enable experimental instant script injection, and append the <style> tag to the documentElement. Add

// @run-at       document-start

and use

document.documentElement.appendChild(document.createElement('style')).textContent = `
ytd-two-column-browse-results-renderer, [id="masthead-ad"] {
  display: none !important;
}
`;

You can do something very similar with an extension designed solely for user-side CSS tweaks, Stylus:

@-moz-document domain("youtube.com") {
  ytd-two-column-browse-results-renderer, [id="masthead-ad"] {
    display: none !important;
  }
}
Related