How to make a word replacement Chrome extension

Nikhil Vijayan
Oct 24, 2018 · 2 min read
Image for post
Image for post

I recently made the ‘Brexit means Breadsticks’ Chrome extension that replaces all mentions of the word ‘Brexit’ with ‘Breadsticks’. Here’s how you can make a similar word replacement extension for Chrome.

First of all, here is the code for it on GitHub. Feel free to use it however you like.

If you’re still reading this, here is how I went about this. This was trickier than I expected, and I didn’t want to use code I found online to do this because, well, it was a weekend project I made for fun and sticking someone else’s code in and calling it a day isn’t as much fun. Also, I’d be lying if I said I understood everything that the ‘cloud to butt’ code did.

Act 1: Failure

const words = [...document.body.getElementsByTagName('*')];

const strip = words.forEach(element => {
element.innerHTML.replace(/Brexit/gi, 'Breadsticks');

Note to self: .replace() does not modify the existing variable, so you need to re-assign it to work.

I also tried

document.body.innerHTML = document.body.innerHTML.replace(/Brexit/gi, 'Breadsticks');

Which I thought was clever. But it kind of breaks the internet if you’re running this code on all pages you load. This will strip off .addEventListener() at best, and break a whole bunch of things I’m not even sure about at worst.

Act 2: Frustration & More Failure

Act 3: Redemption

Here’s the working code. Seeing it work without breaking brought a tear to my eye.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store