DEV Community

Cover image for How To Built A Chrome Extension
Mike Haslam
Mike Haslam

Posted on

How To Built A Chrome Extension

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 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 it got me started and was very helpful. But I wanted to learn more so I went to the Google docs

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
  },
Enter fullscreen mode Exit fullscreen mode

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 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

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

What was the right question? 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
}
Enter fullscreen mode Exit fullscreen mode

Add Your directory as an extension in developer mode

Open the Extension Management page by navigating to
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

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

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
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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();
});

Enter fullscreen mode Exit fullscreen mode

Optional files for later options & popup


If you like to see code here is my repo’s
GitHub - Ongomobile/random-bg-extension

GitHub - 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, Twitter, Facebook, Medium

Cheers,
Mike Haslam

Top comments (0)