Random UTF-8 characters


08 Jan 2016 in xkcdjavascriptchrome

XKCD Substitutions [Chrome Extension]

XKCD was at it again with another funny substitutions comic.


I figured it would be fun to create a Chrome extension that does this. Truth be told there are already a ton of extenstions that do this in the Chrome Store. XKCD even links to the most popular one: XKCD substitutions offered by alec.posney. Since there are already so many competing plugins I decided to do this:


I've never written a Chrome extension before so here we go!

After reading over the Getting Started guide and a little of the documentation. It seemed logical to break this into two parts.

A background file to keep track of the plugins state and a content script to do the substitutions. I also made a few icons to denote the plugins state and of course a manifest file that defines the plugin.

First let's dive into manifest.json:

You can see this defines the name of and default icon of the extension. It also loads up background.js and substitutions.js, where all the work is done.

It also defines what privileges we will need when running. This plugin needs access to:

  • The active Chrome tab.
  • The ability to run a background script.
  • Access to storage to save the plugins state.

The first thing I got working was the ability to store the plugins state and show the correct contextual status icon. This is all handled in background.js.

The code is pretty self explanatory, when the user clicks the icon we toggle the plugins state. We save the new state to local storage and display the correct on or off icon. We also reload the webpage, this is to allow the content script to run if it needs to.

Now for the fun part: substitutions.js. This the content script that does all the on page work. Content scripts do have a limited amount of permissions so I do recommend reading the documentation. In manifest.json we set our content script to run on <all_urls> on the document_idle event. This happens after page content is loaded and javascript has run.

If the plugins state is enabled the makeItBetter function is ran to do all of XKCD's replacements. It walks all the text nodes in the DOM and does a two step replace. I had started with a one step replace but it caused some issues due to "Years ➜ Minutes" and "Minutes ➜ Years".

The results are pretty amusing!

My version is here on GitHub: https://github.com/brookslyrette/chrome-xkcd-substitutions.

All credit for this being interesting or funny goes to XKCD.