How I Created My Own Chrome Extension
I’ve always been curious about how extensions were made. After looking through various online resources, I thought I’d give it a go and have fun while making my very first extension.
What I had in mind was an extension I could turn on, and it would manipulate elements on the website that I’m on. This is DOM (Document Object Model) manipulation. I outlined what my targets were going to be and created a simple outline.
- Select all the Image’s on the current website
- Select all the header tags on the current website
- Change the images to a set image of my choice
- Change the header to another title of my choosing
Before we get into the code, I made a GitHub repository to document the extension code.
Now that I had that ready, I needed to create a manifest.json. This is so the extension can send any relevant data to the browser.
The manifest.json file has the details of the extension (or website, in this case it’s an extension), such as: the name, icons, the url, etc…
Here’s a snippet of how the manifest.json files looks for this particular extension.
Now from the “name” I’m sure you’ve already guessed that my goal is to change all the pictures to pictures of John Snow (Game of Thrones).
Next, let’s create a Content.js file that we’ll use to write our code.
I took the URLs of random John Snow Pictures. At the same time, I created a variable that would represent the elements of the website that are “img” tags.
The code should look like the following:
Next, I used a for loop to loop through the array of John Snow images and set the image on the website to a random image from the array. The for loop looks like this:
Now, this handles the pictures, but I also wanted to target the header tags. Just to be safe, I created variables to refer to any h1, h2, and h3 tags and then I used a similar for loop logic to change the header elements to a string of my choice.
The last bit of code looks like the following:
Now, the code is done. How do I upload the code to chrome?
Go to the extensions on chrome, and enable “Developer Mode” on the top right corner. Now, you’ll be presented with the following selections.
- Load Unpacked
- Pack Extension
Click on Load Unpacked, and select the entire code file from the finder window that opened.
Once that is done, you should be able to see the extension in the list. Here’s how this particular extension would look.
The extension shows as the first extension. Let’s turn it on and test it out on Youtube.
And there you have it, a fun little project where I learned how to create a simple chrome extension .
I hope this article provided some insight, now let’s see what you can make!