Build a Google Chrome Extension
Tags: webdev, javascript, tutorial, html
Published: 2020-10-13 17:58:02

In this article I will show you how to create a simple google chrome extension using [HTML](https://www.programdoc.com/html/intro) and [Javascript](https://www.programdoc.com/javascript/intro) which will show the current time and a random quotes with nature background image.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/56yq9ctntavr91odo5cq.jpg)
Background image will be fetched from **[Pexels](https://pexels.com)**.

### Manifest
First let's create a folder called ChromeExte and then inside create a manifest.json file with the meta details
```json
{
  "manifest_version": 2,

  "name": "Background",
  "description": "Background Image Changer",
  "version": "1.0",
  
  "chrome_url_overrides" : {
    "newtab": "Background.html"
  }
}
```

**chrome_url_overrides** is used to change the default page in chrome, it can be used to change newtab, bookmarks, history  pages. By using a html file.

When a newtab is clicked it will look for the **Background.html**

### Base html
we need to create it inside the ChromeExte directory
```html
<!doctype html>
<html>
  <head>
    <title>Background BG</title>
  </head>
  <style type="text/css">
    body {
      background: url('pexels-photo-775201.jpeg') no-repeat center center fixed;
      -moz-background-size: cover;
      -webkit-background-size: cover;
      -o-background-size: cover;
      background-size: cover;
    }
    .content{
      width: 50%;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    #show_time, #quote {
      color: white;
      text-align: center;
      text-shadow: 2px 2px 5px black;
    }
    #show_time {
      font-size: 55px;
    }
  </style>
  <body>
    
    <div class="content">
      <h1 id="show_time"></h1>
      <h1 id="quote"></h1>
    </div>
    
    <script src="script.js"></script>
  </body>
</html>
```
**body tag** will hold the background image from **[Pexels](https://pexels.com)**.
**show_time** used to show the current system time by using javascript.
**quote** used to show quotes.

Now let's add the functionality to this, for this we need javascript.

### Random quotes logic
quotes will hold the list of quotes, to get the random quote from quotes we used Math in this.

`Math.random()` - will return a random decimal value, multiple it with the length of quotes this will result in some value and then floor the value, it will reduce to lower nearest. Use this value as index to get the quote.
```javascript
const quotes = ["Always believe that something wonderful is about to happen.",
"Act as if what you do makes a difference. It does.", 
"Success is not final, failure is not fatal: it is the courage to continue that counts.", 
"Never bend your head. Always hold it high. Look the world straight in the eye.", 
"What you get by achieving your goals is not as important as what you become by achieving your goals.", 
"When you have a dream, you've got to grab it and never let go.", 
"I can't change the direction of the wind, but I can adjust my sails to always reach my destination.", 
"No matter what you're going through, there's a light at the end of the tunnel.",
"It is our attitude at the beginning of a difficult task which, more than anything else, will affect its successful outcome.",
"Life is like riding a bicycle. To keep your balance, you must keep moving."];

// random quote index
const quotes_i = Math.floor(Math.random() * quotes.length);
// set a quote
document.getElementById("quote").innerHTML = quotes[quotes_i];
```

### Pexels Image 🏜⛰🏔🏕
https://www.pexels.com/api/?locale=en-US
Get the access token to use the api, token has to be passed in the header. We will use plain javascript for Ajax call.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/erqwpgf5pqxegz52bunh.png)

We only get one image per page in the Api. To get the random image `Math.floor(Math.random() * 200) + 1` this will return a value from 0 to 200 use this as page number, you can change the value as you want.

`XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX` replace this with your access token from pexels
```javascript
function loadPexels() {
  var xhttp = new XMLHttpRequest();
  // random page number
  page = Math.floor(Math.random() * 200) + 1
  // get one image per page
  xhttp.open("GET", "https://api.pexels.com/v1/search?query=hd nature wallpaper&per_page=1&page=" + page, true);
  // send Authorization in header
  xhttp.setRequestHeader("Authorization", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
  // response is in json
  xhttp.responseType = 'json';
  xhttp.send();
  
  xhttp.onreadystatechange = function() {
    // when the request is success get the image and update it as background
    if (this.readyState == 4 && this.status == 200) {
      document.body.style.backgroundImage = "url('"+ this.response.photos[0].src.large2x +"')";
    }
  };
}
```
body backgroundImage will get updated.
`this.response.photos[0].src` has the image source with different resolution.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/fkpc46la59og0bjbexd1.png)


### Time shower ⏱ 
using Date method get the current time in AM PM format and set the value to show_time element, we need to update it so call it with setTimeout which is asynchronous function in javascript. It will call the setTime with the interval of 0.5 Sec.

```javascript
// this function is asynchronous
function setTime(){
    t = new Date().toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', second:'numeric', hour12: true });
    document.getElementById("show_time").innerHTML = t;
    // call itself for each 0.5Sec
    var j = setTimeout(setTime, 500);
}
```

### Full JavaScript code
```javascript

const quotes = ["Always believe that something wonderful is about to happen.",
"Act as if what you do makes a difference. It does.", 
"Success is not final, failure is not fatal: it is the courage to continue that counts.", 
"Never bend your head. Always hold it high. Look the world straight in the eye.", 
"What you get by achieving your goals is not as important as what you become by achieving your goals.", 
"When you have a dream, you've got to grab it and never let go.", 
"I can't change the direction of the wind, but I can adjust my sails to always reach my destination.", 
"No matter what you're going through, there's a light at the end of the tunnel.",
"It is our attitude at the beginning of a difficult task which, more than anything else, will affect its successful outcome.",
"Life is like riding a bicycle. To keep your balance, you must keep moving."];

// random quote index
const quotes_i = Math.floor(Math.random() * quotes.length);
// set a quote
document.getElementById("quote").innerHTML = quotes[quotes_i];


function loadPexels() {
  var xhttp = new XMLHttpRequest();
  // random page number
  page = Math.floor(Math.random() * 200) + 1
  // get one image per page
  xhttp.open("GET", "https://api.pexels.com/v1/search?query=hd nature wallpaper&per_page=1&page=" + page, true);
  // send Authorization in header
  xhttp.setRequestHeader("Authorization", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
  // response is in json
  xhttp.responseType = 'json';
  xhttp.send();
  
  xhttp.onreadystatechange = function() {
    // when the request is success get the image and update it as background
    if (this.readyState == 4 && this.status == 200) {
      document.body.style.backgroundImage = "url('"+ this.response.photos[0].src.large2x +"')";
    }
  };
}
// load a random image
loadPexels();

// this function is asynchronous
function setTime(){
    t = new Date().toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', second:'numeric', hour12: true });
    document.getElementById("show_time").innerHTML = t;
    // call itself for each 0.5Sec
    var k = setTimeout(setTime, 500);
}
// set current time
setTime();
```

`script.js`--Linked To-->>`Background.html`--Linked To-->>`manifest.json`
#### File structure
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/29yt6wh4slcge5rlyhx0.png)

To test this working you can just open the html file in browser as normal.

## Add extension to chrome
Go to
**chrome://extensions/**
then enable the Developer Mode, at the top right
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3hrs4bg214svrvk4uhe2.png)
Load the extension, click on Load unpacked
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ojb3i6ntbrw6il8a8hn7.png)
select the `ChromeExte` directory
Extension got loaded
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/m5qjadcgbdbijbgzueb7.png)

## Samples Images

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

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

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


### Thanks you, have a great day ahead.🤪😎