DEV Community

loading...
Cover image for How to make a chrome extension with javascript

How to make a chrome extension with javascript

Ivy Chen
I'm a designer who codes for fun
・4 min read

✨ What you'll be making
In this tutorial, I'll walk you through how to make a chrome extension with vanilla javascript in a few simple steps. The chrome extension that I made gives you a random Chinese idiom every time you open a new tab. But you can easily experiment with quotes or vocabs of another language you want to expose yourself to new words/affirming quotes more often!

✨ First things first: HTML

  <body>
    <div class = "container">
        <div id = "chengyu">
            <h1></h1>
        </div> 
        <div id = "pingyin">
            <h3></h3>
        </div>
        <div id = "definition">
            <h2></h2>
        </div>
    </div>
  </body>  
Enter fullscreen mode Exit fullscreen mode

Remember to link the script.js file and data.json in which you'll create later.

✨ Style it to your taste: CSS
Remember to select the id with a #. I added a line of webkit animation to the body to make the text flow in better.

body {
    color: white;
    font-size: 40px;
    overflow: hidden; /* Hide scrollbars */
    -webkit-animation: fadein 2s; /* Safari, Chrome and Opera > 12.1 */
}
Enter fullscreen mode Exit fullscreen mode

Then you'll need to add these lines in the css as well for the animation to take effect.

@keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}
@-webkit-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}
Enter fullscreen mode Exit fullscreen mode

✨ The fun part: JS
Basically, you write the code in one big function. I first created an array in which I put in some hand-picked colors I'm going to use for the background. Then, there is a general randomize function that returns a random item in the array for you.

    // randomize function 
    function randomize(arr) {
      return arr[Math.floor(Math.random() * arr.length)];
    }
Enter fullscreen mode Exit fullscreen mode

To work with the json file, you use fetch to retrieve it. Underneath .then() is where the majority of the magic happens. You call the randomize function with the data from the json file and assign that to a variable for easier access later on. Then you manipulate the DOM to get the texts to show up randomly together on the HTML.

    // loads the external json file 
    fetch('./data.json')
    .then((response) => {
        return response.json()
    })
    .then((data) => {
    // work with JSON data here
        var random = randomize(data);
    // display the elements on the html
        document.getElementById('chengyu').innerHTML = random.chengyu;
        document.getElementById('definition').innerHTML = random.definition;
        document.getElementById('pingyin').innerHTML = random.pingyin;
    })
    .catch((err) => {
    // do something for an error here
    })
Enter fullscreen mode Exit fullscreen mode

Then the window.onload function is where you put the code for randomly picking a color from the array and displaying it as the background

    //pick a random background color 
    window.onload = function() {
      var randomColor = randomize(color);
      document.getElementsByTagName("body")[0].style.background = randomColor;
    };
Enter fullscreen mode Exit fullscreen mode

Here's the overall code for the JS part!

(function(){
    // array of colors
    var color = [
      "#d1495b",
      "#edae49",
      "#003d5b", 
      "#00509d", 
      "#3a5a40", 
      "#1f7a8c", 
      "#588157", 
    ];
    // randomize function 
    function randomize(arr) {
      return arr[Math.floor(Math.random() * arr.length)];
    }
    // loads the external json file 
    fetch('./data.json')
    .then((response) => {
        return response.json()
    })
    .then((data) => {
    // work with JSON data here
        var random = randomize(data);
    // display the elements on the html
        document.getElementById('chengyu').innerHTML = random.chengyu;
        document.getElementById('definition').innerHTML = random.definition;
        document.getElementById('pingyin').innerHTML = random.pingyin;
    })
    .catch((err) => {
    // do something for an error here
    })
    //pick a random background color 
    window.onload = function() {
      var randomColor = randomize(color);
      document.getElementsByTagName("body")[0].style.background = randomColor;
    };

  })();
Enter fullscreen mode Exit fullscreen mode

✨ The chrome extension part: manifest.json
This is the file that makes the javascript a chrome extension. Customize this to your project needs. Make sure to create an icons folder in your directory and add png of icons in 16px by 16px, 48px by 48px, and 128px by 128px. The description is a one-liner that will show up as a short description when people browse for your extension.

{
  "name": "chengyu",
  "short_name": "chengyu",
  "version": "0.0.1.2",
  "description": "New tab, new Chinese idiom",
  "icons": { "16": "icons/chengyu.png",
             "48": "icons/chengyu-2png", 
             "128": "icons/chengyu-3.png"
           },
  "manifest_version": 2,
  "chrome_url_overrides": {
    "newtab": "index.html"
  }, 
  "web_accessible_resources": [
    "data.json"
]
}
Enter fullscreen mode Exit fullscreen mode

✨ Populating it with content: data.json
This is where you put your JSON objects. Here's an example snippet from my own JSON file to show you the syntax in which you would format it.

[
    {"chengyu": "一了百了", "pingyin": "Yīliǎobǎiliǎo","definition": "When one thing is done, everything is done"},
    {"chengyu": "一刀兩斷", "pingyin": "yīdāoliǎngduà", "definition": "End relationships"},
    {"chengyu": "一口咬定", "pingyin": "yīkǒu yǎodìng", "definition": "Short of something"}
]
Enter fullscreen mode Exit fullscreen mode

✨ Time to try out the extension locally
Go to your manage extensions page and turn on the developer mode. Next, click on load unpacked extension and navigate to the folder that contains your code. Then, you should be able to try out the extension on your Chrome browser. Every time you change the code, it will also be reflected in this developer mode.

🎉 Put it on the Chrome store to share with friends*
To put your extension on the store, you'd need to pay a one-time $5 fee to register a developer account. You'll also need to upload your project to the developer dashboard as a zip file (if you're on mac, compress it and it'll be a zip file). You can follow the quick steps here. It'll take around 1-2 days for the submission to get reviewed and be released on the Chrome store.

Discussion (11)

Collapse
kevinmmansour profile image
Kevin M. Mansour

Awesome article but what about another extensions stores like Microsoft Edge Extensions Store? Is there a fee for joining? Also Is Microsoft Edge Extensions Store support chromium extensions Or they need different setup? Thank you. :)

Collapse
fxnoob profile image
hitesh saini • Edited

they are same! although microsoft edge have its own addon store where you can list your chrome extension. it is because - both browsers are based on chromium engine.

you can also upload your chrome/edge extension to opera store wihtout making any changes as opera is based on chromium too.

As of now, you don't have to pay to list your addon on edge store.

Collapse
kevinmmansour profile image
Kevin M. Mansour

Thank you. :)

Thread Thread
zippytyro profile image
Shashwat Verma

however you need to pay a one-time fee of $5 on Chrome webstore

Thread Thread
kevinmmansour profile image
Kevin M. Mansour

Thank you. :)

Collapse
jonrandy profile image
Jon Randy • Edited

You do realise that essentially all browsers have almost exactly the same extensions API? This extension will work equally well on other browsers. You could make a few minor tweaks to the article, attract a wider audience, and help stop the awful dominance of a single browser engine. It will even work on the best browser - Firefox

Collapse
aboodaud1 profile image
Abood aud

i have a question about extension
lets say i have made a promodo timer extension
when u press on some thing the timer start counting down
but when iam closing the popup it restarting the counter and stop it

Collapse
supritha profile image
Supritha Ravishankar

Using chrome local storage helps resolve this issue

Collapse
waqar profile image
Waqar Ahmed

Great article: you kept it simple, concise and straight to the point.

Collapse
zippytyro profile image
Shashwat Verma

Thanks for writing this! Will try making my first extension soon.
would be great if you add some screenshots.
Anyways, this is great.

Collapse
ivavay profile image
Ivy Chen Author

thanks!! :)