Building Your Very Own Chrome Extension

Yuvraj Singh Pathania
CodeChef-VIT
Published in
7 min readMay 4, 2021

If you are a power web surfer, I'm pretty sure you must use multiple extensions for enhancing your browsing experience. If not, well let me quickly introduce you to a small yet magnificent tool called a Chrome extension(assuming Google Chrome is set as your default browser)

Simply put, Chrome extensions are small programs that add new features to your browser and personalize your browsing experience. This includes adding new features to Chrome or modifying a program’s existing behavior to make it more convenient for the user.

From basic adblockers to email scrapers, extensions have massive utility. But have you ever wondered how exactly are these impressive pieces of technology built?

Well, you’re just at the right place then. I’ll be walking you through the entire process of building your very own extension and even publish it on the chrome store.

Before we start, let's look at some prerequisites :

If you’ve ever built a web page, making an extension would be a piece of cake The only thing you need to learn is how to add some functionality to Chrome through some of the JavaScript APIs that Chrome exposes.

Components of a Chrome Extension ⚙️:

  1. Manifest file:

Every extension has a JSON-formatted manifest file, named, which contains the entire configuration of the extension. Here’s what a basic manifest.json file looks like :

{
"name": "Getting Started Example",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3
}

Depending upon the functionality of the extension, the manifest file would need to include a lot of other parameters such as :

You can read about all of these here

{
// Required
"manifest_version": 3,
"name": "My Extension",
"version": "versionString",

// Recommended
"action": {...},
"default_locale": "en",
"description": "A plain text description",
"icons": {...},

// Optional
"action": ...,
"author": ...,
"automation": ...,
"background": {
// Required
"service_worker":
},
"chrome_settings_overrides": {...},
"chrome_url_overrides": {...},
"commands": {...},
"content_capabilities": ...,
"content_scripts": [{...}],
"content_security_policy": "policyString",
"converted_from_user_script": ...,
"current_locale": ...,
"declarative_net_request": ...,
"devtools_page": "devtools.html",
"differential_fingerprint": ...,
"event_rules": [{...}],
"externally_connectable": {
"matches": ["*://*.example.com/*"]
},
"file_browser_handlers": [...],
"file_system_provider_capabilities": {
"configurable": true,
"multiple_mounts": true,
"source": "network"
},
"homepage_url": "http://path/to/homepage",
"host_permissions": [...],
"import": [{"id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}],
"incognito": "spanning, split, or not_allowed",
"input_components": ...,
"key": "publicKey",
"minimum_chrome_version": "versionString",
"nacl_modules": [...],
"natively_connectable": ...,
"oauth2": ...,
"offline_enabled": true,
"omnibox": {
"keyword": "aString"
},
"optional_permissions": ["tabs"],
"options_page": "options.html",
"options_ui": {
"chrome_style": true,
"page": "options.html"
},
"permissions": ["tabs"],
"platforms": ...,
"replacement_web_app": ...,
"requirements": {...},
"sandbox": [...],
"short_name": "Short Name",
"storage": {
"managed_schema": "schema.json"
},
"system_indicator": ...,
"tts_engine": {...},
"update_url": "http://path/to/updateInfo.xml",
"version_name": "aString",
"web_accessible_resources": [...]
}

2. Content file: A content.js script is “a JavaScript file that runs in the context of web pages.” This means that a content script can interact with web pages that the browser visits. Let's look at a very simple content script that will print “Chrome extension is running!” in the browser console.

// This is the content script for the extension// Things are happeningconsole.log("Chrome extension is running!");

3. Background script: Although the extension has been installed, it has no instruction. Introduce a background script by creating a file titled background.jsand placing it inside the extension directory.

alert("Backround Script running")

4. Popup files: Using basic HTML, CSS and JS we can create a popup page for our extension which will provide a UI for using the extension.

<!--This is the popup  HTML file. It will appear whenever the userpresses the extension button.  It just a plain old web page!But it can communicate with the background and content scripts--><!DOCTYPE html><html><head><meta charset="UTF-8"><title>Extension Pop-Up</title><script src="popup.js" type="text/javascript"></script></head><body><h1>hello</h1></body></html>
This figure gives a great view of the various components of an extension
This figure gives a great view of the various components of an extension

Now that we are accustomed to the basic components of a chrome extension, let's actually start building one!

🦾 🛠

For our first example, let's make an extension that replaces all the images on a webpage with your favorite celebrity/movie character. (keep one ready in mind). I’m choosing Batman, and so I’ll name it Batman-a-nator.

We start with our manifest.json file, which should look something like this :

I have stored all relevant images inside the pics folder within the directory. By convention, we set the version to “0.1”.Also, we keep this extension functional on all webpages, hence we set the parameter “matches” as given below :

{"manifest_version" : 2,"name": "Bataman-a-nator","version": "0.1","web_accessible_resources": ["pics/*.jpg"],"content_scripts": [ {"matches": ["https://*/*"],"js": ["content.js"]} ]}

Next, we create the content.js file. Since this extension only makes changes to the current webpage and is pretty simple, we do not require a background script. Here we chose images at random from the pics folder and replace them with every image visible on the current webpage.

console.log("I'm Batman.....")let filenames = ["batman.jpg","Travis-Scott-.jpg"];let imgs = document.getElementsByTagName('img');for (imgElts of imgs) {// console.log(imgElts.src)let r = Math.floor(Math.random() * filenames.length);let file = 'pics/' + filenames[r];let url = chrome.extension.getURL(file);imgElts.src = url;console.log(url);}

Alright! let's see this in action.

  1. Open Chrome and enter “chrome://extensions”
  2. toggle Developer Mode “ON”
  3. Click on Load unpacked and choose your project Directory
  4. Next pin the unloaded extension in your extension tab
  5. Go on any webpage and see the magic happen

Here’s what youtube.com looks like for me :

Good job, but this was too easy right?

Let's check out another example.

In this example, we will create an on-page dictionary extension. So whatever text you select, the extension will give you a definition for it (if it exists). we will be using the Wordnik API for this.

Overview:

When we select a word on any web page, using the ‘mouseup’ event listener, the content script will extract that particular word and send it to the background script. This message passing will be done using the in-built Chrome APIs. Once the background script receives the selected text, the popup.js file will make a function call to the bg script and get the text element. Now we will pass the received text as an object to the Wordnik API and get the definition for the word and display it on the popup!

Source Code

Publishing your extension on the Chrome Extension store 🛒

We have come to the final step of building an extension, which is, publishing it to the Google Chrome Extension store and putting your product in the hands of, or should I say, clicks of real users.

Simply follow this link to go to your Chrome Web Store dashboard (you’ll have to sign in to your Google account if you haven’t already). Then click the Add new item button, accept the terms and you will go to the page where you can upload your extension. Now compress the folder that contains your project and upload that ZIP file.

After successfully uploading your file, you will see a form in which you should add some information about your extension. You can add an icon, a detailed description, upload some screenshots, and so on.

Make sure you provide some nice images to show off your project. The store can use these images to promote your extension. The more photos you provide, the more prominently your extension will be featured. You can preview how your extension looks inside the web store by clicking the Preview changes button. When you’re happy with the result, hit Publish changes and that’s it, you’re done!

Now go to the Chrome Web Store and search for your extension by its title (It might take some time before it’s up there).

For more help

A snippet of the Google Chrome Extensions Store

Conclusion

As a web developer, it’s very easy to create a Chrome extension in a short amount of time. All you need is some HTML, CSS, JavaScript and basic knowledge of how to add functionality through some of the JavaScript APIs that Chrome exposes. Your initial setup can be published inside the Chrome Web Store within just 20 minutes. Building an extension that’s new, worthwhile, or looks nice will take some more time. But it’s all up to you.

There is literally no barrier to what you want to achieve through an extension, and your creativity is the only limit. I obviously cannot cover every type of extension, but these starter examples will definitely give you the required confidence as well as experience to go on and build any other extension you wish.

So what are you waiting for? It’s time to start working on your own Chrome extension and turning your idea into reality.

Resources:

The best resource for starting out on building Chrome Extensions would be, of course, the Google Chrome extension Docs.

Another fun resource for experimenting with extensions and javascript would be the Coding Train Youtube Playlist.

Thank you for taking the time to read my blog. Cheers 🍻

You can reach out to me through Linkedin 🤝

--

--

Yuvraj Singh Pathania
CodeChef-VIT

Machine Learning Enthusiast, Backend Developer, and part-time DJ