Published on

How to Build Your First Chrome Browser Extension

Authors

Whether you want to automate your day-to-day workflow or you want to customize your favourite website however you want or build a product on top of another project like Twemax

Let's see how to build our own extension.

To keep things simple, let's build a simple extension that changes the favicon of a website.

Let's get started:

Step #1: Creating Manifest File & Configuring It

The very first thing that we'll need is a manifest.json, you can think of this as a config file based on which your browser will run your extension.

In our case,

{
    "manifest_version": 3,
    "name": "Favicon Customizer for Slack",
    "version": "0.0.1",
    "icons": {
        "128": "src/assets/icons8-slack-40.png"
    },
    "content_scripts": [
        {
            "matches": [
                "https://app.slack.com/*"
            ],
            "js": [
                "src/content.js"
            ],
            "run_at": "document_end"
        }
    ]
}

Basically, in content_scripts we've declared the URLs in which our custom javascript needs to be injected in the page when the page is loaded (document_end)

In our case, if the website which we're on is https://app.slack.com then it'll inject our custom JS file which will take care of changing the favicon

Step #2: Injecting Our JavaScript into the Website

Slack changes favicon when we get notification. So to keep things simple, we're updating our icon again with interval (1s). We can use Mutation Observer to watch for changes as well and if it has changed then update our custom favicon again.

let element;
// https://icons8.com/icon/30439/slack
const customIconLink = "https://img.icons8.com/office/40/null/slack.png"

const changeFavicon = () => {
    element = element || document.head.querySelector('[rel="shortcut icon"]');
    if (element && element.getAttribute("href") !== customIconLink) {
        element.setAttribute("href", customIconLink)
    }
}

const intervalId = setInterval(() => {
    element = document.head.querySelector('[rel="shortcut icon"]');
    if (element) {
        changeFavicon()
    }
}, 1000)

Step #3: Installing the Extension & Enabling It

Now go to chrome://extensions and enable the Developer mode if it's not already done.

And then click on Load unpacked and select your browser extension.

Here is a screenshot for your reference. I'm using Brave (a chromium-based browser like Chrome/Opera/Edge) where you can install the chrome extension as well.

And yeah, we're done.

Now you should be seeing your own custom favicon when you use the Slack web app.

I've also created this repo for you to play around with the example.

Happy website customizations!