How to Build a Chrome Extension
Tags: javascript, showdev
Published: 2020-10-31 10:16:30



{% spotify spotify:episode:71N85CPF4G1wQXWXLZcD7a?si=dAlYRQhZQb2qc5ZEagUWeA %}




Chrome extensions are small HTML, CSS and JavaScript apps that we can install in the chrome browser.

In this tutorial, We are going to build an extension that allows users to get covid19 case details based on the **country** selected.
<hr>
![h8znwg5mm0a1ax96ge0p.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1604098476709/ut847kghI.jpeg)

<b>Step 1:</b> Create a new directory "dist" and create files under that directory as shown in the picture

![screely-1604097689947.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1604097741972/GO8z6Z3dR.png)


<b>Step 2:</b> Create an HTML file

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Covid 19</title>
    <link rel="stylesheet" href="./style.css" />
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script type="text/javascript" src="index.js" defer></script>
  </head>
  <body>
    <div class="header">Covid 19</div>
    <div class="container">
    <form class="form-data" autocomplete="on">
      <div class="enter-country">
        <b>Enter a country name:</b>
      </div>
      <div>
        <input type="text" class="country-name" />
      </div><br>
      <button class="search-btn">Search</button>
    </form>
    <div class="result">
      <div class="loading">loading...</div>
      <div class="errors"></div>
      <div class="data"></div>
      <div class="result-container">
        <p><strong>New cases: </strong><span class="todayCases"></span></p>
        <p><strong>New deaths: </strong><span class="todayDeaths"></span></p>
        <p><strong>Total cases: </strong><span class="cases"></span></p>
        <p><strong>Total recovered: </strong> <span class="recovered"></span></p>
        <p><strong>Total deaths: </strong><span class="deaths"></span></p>
        <p><strong>Total tests: </strong><span class="tests"></span></p>
        <center><span class="safe">Stay Safe and Healthy</span></center>
      </div>
    </div>
  </div>
</body>
</html>
```

<b>Step 3:</b> Create a js file to handle API calls

``` javascript
const api = "https://coronavirus-19-api.herokuapp.com/countries";
const errors = document.querySelector(".errors");
const loading = document.querySelector(".loading");
const cases = document.querySelector(".cases");
const recovered = document.querySelector(".recovered");
const deaths = document.querySelector(".deaths");
const tests=document.querySelector(".tests");
const todayCases=document.querySelector(".todayCases");
const todayDeaths=document.querySelector(".todayDeaths");
const results = document.querySelector(".result-container");
results.style.display = "none";
loading.style.display = "none";
errors.textContent = "";
// grab the form
const form = document.querySelector(".form-data");
// grab the country name
const country = document.querySelector(".country-name");

// declare a method to search by country name
const searchForCountry = async countryName => {
  loading.style.display = "block";
  errors.textContent = "";
  try {
    const response = await axios.get(`${api}/${countryName}`);
    if(response.data ==="Country not found"){ throw error;  }
    loading.style.display = "none";
    todayCases.textContent = response.data.todayCases;
    todayDeaths.textContent = response.data.todayDeaths;
    cases.textContent = response.data.cases;
    recovered.textContent = response.data.recovered;
    deaths.textContent = response.data.deaths;
    tests.textContent =  response.data.totalTests;
    results.style.display = "block";
  } catch (error) {
    loading.style.display = "none";
    results.style.display = "none";
    errors.textContent = "We have no data for the country you have requested.";
  }
};

// declare a function to handle form submission
const handleSubmit = async e => {
  e.preventDefault();
  searchForCountry(country.value);
  console.log(country.value);
};

form.addEventListener("submit", e => handleSubmit(e));
```

We have an asynchronous function called searchForCountry and within that function, we can use async-await. Async await allows us to stop executing code that is dependent, while we wait for the response from a server. By using the await keyword in front of a piece of code we can get the rest of our code to stop executing while that piece of code executes.

In this example, we await a response from our GET request before setting that response to our articles variable.

Axios is a very popular JavaScript library you can use to perform HTTP requests, that works in both Browser and Node.js platforms. It supports all modern browsers, including support for IE8 and higher. It is promise-based, and this lets us write async/await code to perform XHR requests very easily.

<h4>Here are some endpoints to access data via API</h4>
<ul>
<li><a href="https://coronavirus-19-api.herokuapp.com/countries">https://coronavirus-19-api.herokuapp.com/countries</a> - To get details about all countries</li>
<li><a href="https://coronavirus-19-api.herokuapp.com/countries/india">https://coronavirus-19-api.herokuapp.com/countries/india</a> - To get covid19 cases details specific to **India**</li>
</ul>

<b>Step 4:</b> You can also add css to your HTML file

<b>Step 5:</b> Create manifest.json and add following code. This is the file that contains information on how Chrome should handle the extension.

```javascript
{
    "manifest_version": 2,
    "name": "Covid19",
    "version": "1.0.0",
    "description": "Provides the cases details regarding Covid19 with respective to any Country",
    "browser_action": {
      "default_popup": "index.html"
    },
    "icons":{
      "16": "./icons/16covid-19.png",
      "64": "./icons/64covid-19.png",
     "128": "./icons/128covid-19.png"
    },
    
    "content_security_policy": "script-src 'self' https://unpkg.com ; object-src 'self'"
  }
```
<b>manifest_version, name and version</b> are important and MUST be declared. The extension must have a manifest_version of 2 to work with the latest Chrome browsers, you can give it whatever name/version you wish.

![alt-txt](https://media.giphy.com/media/mo2WzZzncObfXfc49n/giphy.gif)
<hr>
<h2><b>Adding Extension to Chrome:</b></h2>
Go the Chrome Extensions or you can click on this <a href="chrome://extensions/">chrome://extensions</a> to navigate to the extension page.
Once the page is opened, click on **load unpacked** and locate extension package.

I recently submitted this extension for review and it's pending for approval.

*Hope Google approves it* :) 

![2.PNG](https://cdn.hashnode.com/res/hashnode/image/upload/v1604098909730/cYGYLMY8I.png)

**Here is the working video of Covid19 Extension**

{% youtube ppFkyHGS1ys %}

**Hope it's useful**

**A ❤️ would be Awesome** 😊