Building a Chrome Extension using DEV API
Tags: javascript, html, productivity, tutorial
Published: 2020-10-01 11:04:05

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 articles based on tags from dev.to by simply selecting it.

As we are using <b>get</b> requests method we don't need an API key from dev.to 
Check out <a href="https://docs.forem.com/api/">DEV API docs</a> and get your hands dirty

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

You can find all the necessary code and files from my <a href="https://github.com/aletisunil/DEV_Extension">GitHub Repository</a>
{% github aletisunil/DEV_Extension no-readme %}


<hr>

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4e6yqjgfzsmmso4i0boy.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>Document</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>
    <label><center><b>DEV</b></center></label>
    <p>An Extension which pulls out articles based on tags</p>
    <div class="container">
    <form  id="form-data">
      <label for="tags">Select a tag:</label><br><br>
        <select name="tags" id="tags">
          <option disabled selected value> -- select an option -- </option>
          <option value="python">Python</option>
          <option value="javascript">Javascript</option>
          <option value="tutorial">Tutorial</option>
          <option value="productivity">Productivity</option>
          <option value="discuss">Discuss</option>
          <option value="beginners">Beginners</option>
          <option value="archlinux">archlinux</option>
          <option value="webdev">Webdev</option>
          <option value="android">Android</option>
          <option value="react">React</option>
        </select><br><br>
      <button type="submit" class="seach-btn">Submit</button>
    </form>
    <div class="result">
     </div>
    </div>
  </div>
  </body>
</html>
```

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

``` javascript
const results = document.querySelector(".result");
const api = "https://dev.to/api/articles?tag=";
const search = document.getElementById("form-data");

const getposts = async (Tag) => {
    try {
      const tag = await document.getElementById("tags").value;
      const response = await axios.get(`${api}${tag}`+"&per_page=5");
      
      var articles="";
        if(response.data.length!=0){
            for(var i=0;i<response.data.length;i++){
                articles+='<li><a href='+response.data[i].url+'>'+response.data[i].title+'</a></li>';
            }
        link="https://dev.to/t/"+tag
        articles+='<br><center><a href='+link+'>Checkout blog</a><center>';
      }
        results.innerHTML=articles;
    }
      catch (error) {
      console.log("error")
    }
  };
  // declare a function to handle form submission
  const handleSubmit = async e => {
    e.preventDefault();
    getposts(tags);
    
  };
  search.addEventListener("submit", e => handleSubmit(e));
```

We have an asynchronous function called getposts 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 articles, users and other resources via API</h4>
<ul>
<li><a href="https://dev.to/api/articles">https://dev.to/api/articles</a> - To get published articles</li>
<li><a href="https://dev.to/api/articles?username=sunilaleti">https://dev.to/api/articles?username=sunilaleti</a> - To get user specific published articles</li>
<li><a href="https://dev.to/api/articles?tag=tutorial">https://dev.to/api/articles?tag=tutorial</a> - To get articles based on <b>tutorial</b> tag
<li><a href="https://dev.to/api/articles?tag=python&top=5">https://dev.to/api/articles?tag=python&top=5</a> - To get most popular posts based on python tag in the last 5 days</li>
</ul>

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

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

<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": "DEV",
    "version": "0.1.0",
  
    "permissions": ["<all_urls>"],
  
    "browser_action": {
      "default_popup": "index.html"
    },
    "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.

We set permissions to all_urls so that our extension can run on any page. browser action instructs chrome to show our index.html file as a popup when the icon is clicked.

![alt-txt](https://media.giphy.com/media/3mqkm10jCRkhP9HoFL/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/">link</a> to navigate to the extension page.
Once the page is opened, follow the video to add it
{% youtube 2bM0JD4OLyc %}
<br>

<b>If you like my content, please consider supporting me</b><br>
<a href="https://www.buymeacoffee.com/sunilaleti" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-black.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a><br>

<b>My level of happiness rose to ecstatic, as I recently crossed 1000 followers and 25000 post views on DEV.
Thanks to DEV Team and Everyone who supported me</b>

Hope it's useful

A ❤️ would be Awesome 😊