What is Tampermonkey?

Tampermonkey is a browser extension that makes my life easier, on a daily basis. It allows you to easily write your own userscripts and have them execute whenever you deem fit. Tampermonkey can be used to revamp websites, add features, delete features, automate.

Very often I’d say to myself, “I wish an extension existed that did X”, most of the time X is so trivial that it can be written in 5 minutes with Tampermonkey, no need to go through the laborious process of writing your own Plugin.

Tampermonkey has a brilliant feature where you can search for other scripts for specific websites using Greasy Fork — the Github for userscripts. Just a quick search and you’ll be surprised how often an issue you have with a website has already been solved with a userscript. Tampermonkey leverages userscript.zone to do the search lifting.

In this blog I’ll show you how you can write a userscript to remove ads from a particular website.

Writing your first script

My favourite blogging website of all time has got to be Coding Horror, as of writing this blog, the site has very discrete ads by Carbon — of which, I am also a fan. But let’s pretend, for the sake of this example that the adverts were dramatically intrusive, and I wanted them gone. This would be a perfect use-case for writing a Tampermonkey userscript.

The Carbon ads are there on the left.

With the website we want to write the script for — https://blog.codinghorror.com/ — open, let’s open up our editor by clicking the Tampermonkey icon and hitting Create a new script:

Your code should look like this:

// ==UserScript==
// @name         Coding Horror Remove Ads
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://blog.codinghorror.com/
// @icon         https://www.google.com/s2/favicons?domain=codinghorror.com
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Your code here...
})();

Notice how it’s already plugged in the website in the @match comment, as to say this script will be executed when on that website.

Note, I’ve also edited the @name comment, so we can easily identify our userscript later.

If you save by hitting ctrl+s and navigate back to https://blog.codinghorror.com/ you’ll see a number 1 on the google chrome extension:

To let you know that Tampermonkey is working on this website. If you click the icon you can see which script you’ve got running:

The script ran, but of course, I haven’t written any code yet. Let’s open the editor back up and start writing!

First of all, let’s find out how we can remove the ads, there’s two ways I can think of:

  1. Remove the ad element from the page
  2. Intercept the request to get the ad content

Let’s start off with step 1 as that’s probably going to be easier.

Removing the ad content

When inspecting the element I can see there’s a div with an id of #carbonads.

We can simply select this element in the DOM, and remove it:

document.getElementById('carbonads').remove(); // should do the trick

Let’s run this first in our console and see if it works:

Brilliant, we’ve got some working code, let’s plug it into our userscript.

// ==UserScript==
// @name         Coding Horror Remove Ads
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://blog.codinghorror.com/
// @icon         https://www.google.com/s2/favicons?domain=codinghorror.com
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    document.getElementById('carbonads').remove()
    // Your code here...
})();

And reopen the website:

Oh no, we’ve got an error and the ads still there? 🤦‍♂️

Our script is running before the website has even fetched the advert, so the code document.getElementById('carbonads') returns a null.

Let’s wait for the website to load, then remove the element:

// ==UserScript==
// @name         Coding Horror Remove Ads
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://blog.codinghorror.com/
// @icon         https://www.google.com/s2/favicons?domain=codinghorror.com
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    window.addEventListener('load', (event) => {
        console.log('loaded, now removing')
        document.getElementById('carbonads').remove()
    });
})();

And now opening the website:

So you can see it waits for the document to fully load then it removes it. Rubbish. We want it to be gone without us knowing it was ever there.

Let’s add some code that specifically waits for the carbonads element to display:

// ==UserScript==
// @name         Coding Horror Remove Ads
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://blog.codinghorror.com/
// @icon         https://www.google.com/s2/favicons?domain=codinghorror.com
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    waitForElementToDisplay('carbonads', () => document.getElementById('carbonads').remove());
})();

function waitForElementToDisplay(elementId, callback) {
    let interval = setInterval(() => {
        if (document.getElementById(elementId) != null) {
           callback();
           clearInterval(interval);
        }
    }, 10);
}

Here I’ve created a function which takes the elementId and a callback as arguments. In the function I’m simply setting an interval that continuously checks to see if the element exists, and when it does I call the callback and clear the interval. The callback code is exactly the same as we had before, just deleting the element.

Now, when opening up the website we shouldn’t see the ads, and we also shouldn’t see it pop up for a second and get removed.

There is one problem though…

Running the script on every page

At the moment our script only executes on the home page – https://blog.codinghorror.com/. So when we navigate to a different page, we can still see the ads.

E.g. https://blog.codinghorror.com/building-a-pc-part-viii-iterating/:

Simply editing the @match tag of the userscript comment/config does the trick here:

// @match        https://blog.codinghorror.com/*

Now when we navigate to any blog on the page our script will run! Perfect.

I hope you enjoyed this blog, I have plans to do more on Tampermonkey as friends from the newsletter seemed intrigued when I mentioned it in my previous blog.

Leave a Reply