How To Built A Chrome Extension
Tags: javascript, html, tutorial
Published: 2020-12-31 21:15:19

My inspiration was my Love of Thailand and curiosity about a new rabbit hole.

I was doing my normal routine when I came across the [Momentum](https://momentumdash.com/) Chrome extension. It was very inspiring and totally worth the pro price.
So my analytical mind said it would be fun to reverse engineer this.

So I did what most people do and did a search on google. My first query was how to create a chrome extension.  What I found initially that caught my attention was a post on Medium by [Andrei Elekes](https://medium.com/coding-in-simple-english/how-to-create-chrome-extension-7dd396e884ef) it got me started and was very helpful. But I wanted to learn more so I went to the [Google docs](https://developer.chrome.com/docs/extensions/mv3/getstarted/)

Having not built a Chrome Extension before, I did what most developers do to get familiar and I started to build the Hello World version from the docs. 

I got into the first couple of steps then encountered my first error, hey no problem I thought let's just read it?

“**The “background.scripts” key cannot be used with manifest_version 3. Use the “background.service_worker” key instead.”**

What I found after researching and banging around a bit was google is in the process of implementing V3 that uses services workers instead of background. 

This is one of V3 changes, but in the getting started tutorial in the manifest file it says “manifest_version”: 3 but it still had the V2 

```
background”: {
    “scripts”: [“background.js”],
    “persistent”: false
  },
```
Seeing that as of 12/29/20 the getting started tutorial has not been updated, I decided just to go forward with the getting started tutorial in manifest  V2   **The answer to the initial error for me is just declaring “manifest_version”: 2**

After finding focus again and wanting to close this rabbit hole. I decided I wanted to create a basic Chrome Extension using manifest V3 that would load a random background Image in the chrome browser tab. **Details Below** To continue to get familiar I continued with the [getting started tutorial in the docs](https://developer.chrome.com/docs/extensions/mv3/getstarted/) It’s actually quite good and easy to follow in the context of manifest V2. 

Rather than re-creating each step, this is what I found it gives you the fundamentals and is not hard to implement. In the end, it has a popup and has a button you can change colors in options this is great to understand the fundamentals. 

I was hungry for more so in my digging I discovered this file in google docs.
[GitHub - GoogleChrome/chrome-extensions-samples: Chrome Extensions Samples](https://github.com/GoogleChrome/chrome-extensions-samples)

In the tutorials section, the get_started_complete file you can see the popup.js has a variation where the onclick listener can change the background color of the URL that is listening for the message in background.js

**So how did I make my simple extension that adds a random background image on chrome browser?**

First I did what most developers do I googled. In the end, what I found was if I asked the right question sooner it would have been much quicker to find the solution. 

It was actually quite simple in that I had already written the code for setting a random Image on the body tag in the first single-page JavaScript app I built  [Thailand explorer](https://www.thailandexplorer.org/)

What was the right question?  [How to create a chrome extension to change the default tab](https://stackoverflow.com/questions/39916079/how-to-create-a-chrome-extension-to-change-the-default-tab) 

## Steps to create random image background extension version1.0

Set up file structure root directory folder, images folder, manifest.json, newTab.html, newTab.css, newTab.js. **Optional Files to use later** options.html, options.js, popup.html, popup.js

**Create the  initial manifest**   

``` 
{
  “name”: “Random Image”,
  “version”: “1.0”,
  “description”: “A random  background image generator”,
  “manifest_version”: 3
}
```




**Add Your directory as an extension in developer mode** 

Open the Extension Management page by navigating to 
          [chrome://extensions](chrome://extensions/)

Enable Developer Mode by clicking the toggle switch 
            next to **Developer mode**.

 Click the **LOAD UNPACKED** button and select the 
            extension directory.

 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/rir8yu21ytszqdu7bfys.png)

        
**Add icons**  You can create your own or grab these from the Google getting started tutorial. Here is a link to docs on sizes and what they are for. [Icon Docs](https://developer.chrome.com/docs/extensions/mv3/user_interface/#icons)

**Update manifest.json**  

```
{
  “name”: “Random Image”,
  “version”: “1.0”,
  “description”: “A random  background image generator”,
  “chrome_url_overrides”: {
    “newtab”: “newtab.html”
   },
   “action”: {
    “default_icon”: {
      “16”: “images/icon16.png”,
      “32”: “images/icon32.png”,
      “48”: “images/icon48.png”,
      “128”: “images/icon128.png”
    },
    “default_title”: “Random Image”,
    “default_popup”: “popup.html”
   },
   “icons”: {
    “16”: “images/icon16.png”,
    “32”: “images/icon32.png”,
    “48”: “images/icon48.png”,
    “128”: “images/icon128.png”
   },
    “manifest_version”: 3
}
```

**Create newTab.html** 
```
<!DOCTYPE html>
<html lang=“en”>
  <head>
    <meta charset=“UTF-8” />
    <meta name=“viewport” content=“width=device-width, initial-scale=1.0” />
    <title>Thailand Images</title>
    <link rel=“stylesheet” href=“newTab.css” />
  </head>
  <body class=“pageBody”>
    <script src=“newTab.js”></script>
  </body>
</html>
```


**Create newTab.css**

```
body {
  background: linear-gradient(rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4)),
    url(“https://thailand-exp-images.s3-us-west-2.amazonaws.com/komloy.jpg”);
  background-repeat: no-repeat;
  background-size: cover;
}
```

**Create newTab.js** 

```
const pageBody = document.body;
const ready = (callback) => {
  if (document.readyState != “loading”) callback();
  else document.addEventListener(“DOMContentLoaded”, callback);
};

// TODO: Add images dynamically from extension settings
const setRandomImage = () => {
  const IMG_URL = “https://thailand-exp-images.s3-us-west-2.amazonaws.com/“;
  const backgroundImages = [
    “riceLady.jpg”,
    “raileyBeach.jpg”,
    “monksTemple.jpg”,
    “monkeys.jpg”,
    “manChang.jpg”,
    “maeYai.jpg”,
    “girlsWater.jpg”,
    “girlChang.jpg”,
    “floatingMarket.jpg”,
    “buddha.jpg”,
    “boyBudah.jpg”,
    “ancient.jpg”,
    “thaiBackground.jpg”,
    “Yipeng.jpg”,
    “islands.jpg”,
    “Loy_Krathong.jpg”,
    “thaiBudah.jpg”,
    “komloy.jpg”,
  ];

  const randomImage =
    backgroundImages[Math.floor(Math.random() * backgroundImages.length)];
  pageBody.style.backgroundImage = `url(${IMG_URL}${randomImage})`;
};

ready(() => {
  setRandomImage();
});

```

Optional files for later options & popup
- - - -
If you like to see code here is my repo’s
[GitHub - Ongomobile/random-bg-extension](https://github.com/Ongomobile/random-bg-extension)

[GitHub - Ongomobile/change-bg-color-chrome-extension](https://github.com/Ongomobile/change-bg-color-chrome-extension)

**The next challenge is to add images in options or popup and not be dependent on hardcoded images.**

I hope this has been helpful please feel free to reach out with feedback or questions.

If you would like to learn more you can find me on: 
[LinkedIn](https://www.linkedin.com/in/ongo-mobile/), [Twitter](https://twitter.com/OngoMobile), [Facebook](https://www.facebook.com/ongomobile), [Medium](https://ongomobile.medium.com/)

Cheers,
Mike Haslam