Create a Chrome Extension to hide YouTube Comments

11 September 2014

Project Definition

Today we will go through how we can create a very basic Chrome Extension called NoComment that hides the comments section on YouTube.

The Chrome Extension will hide the comments on YouTube.com on page load. It then displays an icon in the addressbar allowing you to click on it to toggle the visibility of the comment section should you wish to see the comments for a particular video.

Once completed you can browse YouTube without being bombarded with the very worst comments to be found on the Internet. Bliss.

Basic Project Setup

To create our basic Chrome Extension we need the following files:

  • manifest.json
  • images/icon-19.png
  • images/icon-48.png
  • images/icon-128.png
  • background.js
  • content.js

You can find the source code for the NoComment Chrome Extension on GitHub.

Manifest.json

Each Chrome Extension requires, as a minimum, a manifest.json file. Note that this is the only file in the extension with a strict filename requirement.

The configuration of the extension itself is defined within the manifest file using JSON format. The name, version and manifest_version are required fields, but we'll be adding in a few others to get our extension to actually do something.

Name is the name of your extension - NoComment in our example. Version is your own defined version number. Manifest_Version is a Google-defined configuration that should be set to 2 as manifest version 1 has been deprecated.

Here is the manifest.json file we'll be using in your extension:

{
  "name": "NoComment",
  "version": "1.0.0",
  "manifest_version": 2,
  "description": "Toggle comment visibility on YouTube.com",
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "page_action": {
    "default_icon": "icon-19.png",
    "default_title": "Toggle YouTube comments"
  },
  "permissions": ["declarativeContent", "activeTab"],
  "content_scripts": [
    {
      "matches": ["*://*.youtube.com/*"],
      "js": ["content.js"],
      "run_at": "document_end"
    }
  ],
  "icons": {
    "48": "icon-48.png",
    "128": "icon-128.png"
  }
}

Types of Chrome Extensions

Extensions impact the browser UI in two distinct ways:

  • Browser Actions
  • Page Actions

The Browser Action extensions are the types you may already be familiar with that provide an icon that is always visible in the browser's primary toolbar. You are advised to use a Browser Action when the functionality is relevant to most pages you visit (e.g. Save To Pocket). More info can be found at the browserAction documentation on the Chrome site.

The Page Action extensions, however, display their icon in the address bar itself. It is advised that you use the Page Action style extension on functionality that is only relevant to some pages (e.g. to hide comments on youtube.com only). More info can be found at the pageAction documentation on the Chrome site.

The NoComment extension will be a PageAction type. As such we add the following configuration to our manifest file to define the icon displayed in the addressbar.

  "page_action" :
  {
    "default_icon" : "images/icon-19.png",
    "default_title" : "Toggle YouTube comments"
  },

Content Script

Next up we'll create the Content Script by creating a file named content.js within our extension folder. The name of this file doesn't really matter so you can call it anything you want as it will be referenced within our manifest.json file.

The content script is run on each page load where relevant and is used to manipulate the DOM within the current browser tab's content.

Our content.js file contains a simple function to toggle the styling to display none on the content div. We also run the function so as to trigger the function to hide the contents on page load.

showHide();

function showHide() {
  var el = document.getElementById('watch-discussion');
  if (el && el.style.display == 'none') el.style.display = 'block';
  else if (el) el.style.display = 'none';
}

We add the following to our manifest configuration to ensure our extension knows which script to run.

  "content_scripts":
  [
      {
          "matches": ["*://*.youtube.com/*"],
          "js": ["content.js"],
          "run_at": "document_end"
      }
  ],

The matches field is used to restrict the execution of the content script to only pages that match the regex used. We could use "*://*/*" if we wanted it to match on all pages, or (as we have used) "*://*.youtube.com/*" to target only YouTube pages.

The js field defines the script file that will be run on matched pages. We set that to our content.js file but this would be the same as the name you chose earlier.

Lastly, the run_at field allows us to ensure the execution of the content script is deferred to the end of the page load.

More info can be found at the Content Scripts documentation on the Chrome site.

Background Script

The background script can be thought of as our extension's initiliaser or constructor. We have named our background script background.js but you may name it anything you wish.

Our background script contains some simple initialisation code and a Listener for the action of clicking on the addressbar icon.

// When the extension is installed or upgraded ...
chrome.runtime.onInstalled.addListener(function() {
  // Replace all rules ...
  chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
    // With a new rule ...
    chrome.declarativeContent.onPageChanged.addRules([
      {
        // That fires when a page's URL contains 'youtube.com'...
        conditions: [
          new chrome.declarativeContent.PageStateMatcher({
            pageUrl: { urlContains: 'youtube.com' },
          }),
        ],
        // And shows the extension's page action.
        actions: [new chrome.declarativeContent.ShowPageAction()],
      },
    ]);
  });
});

chrome.pageAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(null, { file: 'content.js' });
});

Make note of the line where we define the URL to which this page action is valid (namely youtube.com). This means that the icon will only be visible in the addressbar when we are browsing pages within that defined URL.

Also note the Listener that executes the content.js script when the page action icon is clicked. Recall that this script contains the function to toggle the visibility of the YouTube comments which is executed when the content script is run.

We add a few lines to our manifest file to ensure our extension knows which script to run for background tasks.

  "background":
  {
    "scripts": ["background.js"],
    "persistent": false
  },

We set persistent to false to ensure the background script is active only when required. This saves on resources and is the method prescribed by Google unless persistence is indeed a neccessity. In fact, setting the persistence to false means we have created a very specific type called Event Pages. To quote the Chrome documentation "Persistence is what differentiates an event page from a background page."

As always, more info can be found at the Event Pages and Background Pages documentation on the Chrome site.

Install your extension

To install the extension you will first need to navigate to chrome://extensions in Chrome or alternatively click on the hamburger menu, select Tools and then Extensions.

Now click on the button reading Load unpacked extension... and browse to your extension's folder before clicking on Select.

If there are any errors then Chrome will highlight those but if you followed the instructions above you should now have a Chrome Extension that hides those pesky YouTube comments by default.

Now go enjoy your new, clean, distraction-free YouTube!

Share this article
Was this post helpful?
Buy me a coffeeBuy me a coffee