How To Create A Simple Google Chrome Extension

Browser extensions are small software modules that we can use for the customization of the browsers. Also, we can use these extensions to display customized tabs or play some music in the background, etc. Implementing a simple google chrome extension is an easy task.

In this article, we will learn how to create a simple Google chrome extension.

This extension opens whenever we open a new google chrome tab.

The extension calls a REST API provided by https://www.boredapi.com and displays a random activity suggestion.

It’s a free API that suggests some cool activities every time we hit the API.

Table of Contents

Creating simple google chrome extension

Create a folder with the name ActivitySuggestionApp. This folder will contain all the files related to our chrome extension.

The manifest.json file

Create a manifest.json file and add the below content.

The JSON file contains all the necessary details about the chrome browser extension. It provides the required metadata like the name of the browser extension, version details, icon image, etc.

{
    "name": "Activity suggestions app",
    "version": "1.0",
    "description": "Activity suggestion extention for chrome!",
    "chrome_url_overrides":{
        "newtab":"activities.html"
    },
    "background" : {
        "scripts" : [ "background.js" ],
        "persistent" : false
    },
    "manifest_version": 2
}

We can use the name, version, and description properties to provide the extension details.

Also, we can use the newtab property of the chrome_url_update property to specify the custom HTML file that loads on opening the new chrome tab. We will load the activities.html file whenever the user opens a new tab.

Also, we can use the background property to perform any background activities and the scripts property value with background.js.

This script will call the REST API to fetch the activity every time a new chrome tab opens.

Adding extension Icon

We will use the below png image file as the extension’s icon and default_icon image.

google chrome icon image

We can use the icon property to change the icon that the extension page(available at chrome://extensions/) displays.

Add the below properties to the manifest.json file.

"icons" : { 
        "16" : "activity.png",
        "48" : "activity.png",
        "128" : "activity.png"
},

We can provide different dimensions of icons to our extension(In this example, we will use the same icon image for all dimensions).

google chrome extension icon image

Let us use the same image file to set the default_icon property of the browser_action property.

"browser_action": {
    "default_icon": "activity.png"
}

The icon will be displayed as shown below.

chrome extension browser action icon image.

Creating the main app logic

Let us now create the necessary HTML, CSS, and javascript files.

Create an activities.html file and add the below content.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8"/>
        <title>Activity Suggestion</title>
        <link rel="stylesheet" href="activity.css">
    </head>
    <body>
        <h3>Hi There!!</h3>
        <h3>I have an activity suggestion for you!</h3>
        <div class="card">
            <div class="container">
                <div class="loader"></div>
                <p></p>
                <a></a>
            </div>
          </div>
        <script src="activity.js"></script>
    </body>
</html>

We will create a web page to display a header and an activity card with a description and a link, if available. We use REST API to fetch the activity details.

Create an activity.js javascript file.

//send message to background
chrome.runtime.sendMessage({name: "fetchTask"}, (response) => {
    document.querySelector('.loader').style.display = "none";
    document.querySelector('p').innerHTML=response.activity;
    if(response.link != '' || response.link != null){
        document.querySelector('a').href=response.link;
        document.querySelector('a').innerHTML=response.link;
        document.querySelector('a').target="_blank";
    }
})

This script file is invoked on page load and uses chrome.runtime.sendMessage to send a message to load the activity detail from REST API.

The page displays a spinner on the page and shows the activity details once the response is available.

Calling the Web API from background

Create a background.js file and add the below content.

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
    const url = "https://www.boredapi.com/api/activity?participants=1";
    if(msg.name === "fetchTask") {
        fetch(url)
            .then(response => response.json())
            .then(data => sendResponse(data))
            .catch(error => alert("Something went wrong!!" + error));
            return true;
    }
})

This file uses chrome.runtime library to listen to the message sent from the activity.js javascript file.

Once the script receives the message with name property value as fetchTask, the backend API retrieves the activity details.

Finally, the below snippet shows the API response format.

{
  "activity": "Go on a long drive with no music",
  "type": "relaxation",
  "participants": 1,
  "price": 0.1,
  "link": "",
  "key": "4290333",
  "accessibility": 0.2
}

We use only the activity and link properties of the JSON response in our extension.

The JSON response returned to the activity.js file to display the activity details on the new chrome tab.

Adding style to chrome extension

Create a new CSS file with the name activity.css and add the below content.

body, html {
    display: flex;
    background-color:azure;
    font-size: x-large;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    min-height: 100%;
}
div {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    position: relative;
}
p, a {
    word-break: break-all;
    position: relative;
    justify-content: center;
    vertical-align: middle;
}
.card {
    background-color: blanchedalmond;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.5);
    transition: 0.3s;
    width: 100%;
    display:block;
    width:100%;
    height: 5em;
    background-color:rgb(248, 255, 154);
    padding-bottom: 5em;
}
.card:hover {
    box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.856);
}
.container {
    padding: 2px;
}
/*loader CSS*/
.loader,
.loader:before,
.loader:after {
  border-radius: 50%;
}
.loader {
  color: #ffffff;
  font-size: 11px;
  text-indent: -99999em;
  margin: 55px auto;
  position: relative;
  width: 10em;
  height: 10em;
  box-shadow: inset 0 0 0 1em;
  -webkit-transform: translateZ(0);
  -ms-transform: translateZ(0);
  transform: translateZ(0);
  z-index:5;
}
.loader:before,
.loader:after {
  position: absolute;
  content: '';
}
.loader:before {
  width: 5.2em;
  height: 10.2em;
  background: #0dc5c1;
  border-radius: 10.2em 0 0 10.2em;
  top: -0.1em;
  left: -0.1em;
  -webkit-transform-origin: 5.1em 5.1em;
  transform-origin: 5.1em 5.1em;
  -webkit-animation: load2 2s infinite ease 1.5s;
  animation: load2 2s infinite ease 1.5s;
}
.loader:after {
  width: 5.2em;
  height: 10.2em;
  background: #0dc5c1;
  border-radius: 0 10.2em 10.2em 0;
  top: -0.1em;
  left: 4.9em;
  -webkit-transform-origin: 0.1em 5.1em;
  transform-origin: 0.1em 5.1em;
  -webkit-animation: load2 2s infinite ease;
  animation: load2 2s infinite ease;
}
@-webkit-keyframes load2 {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
@keyframes load2 {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

Running simple google chrome extension

To run the extension, open chrome://extensions/ on a new browser tab and click on the Load unpacked button, and select the extension folder(ActivitySuggestionApp).

loading unpacked chrome extension.

Once the extension is loaded, it will be available on the extension list, as shown below.

google chrome extension activity suggestion.

Open a new tab on the chrome browser window, and we should be able to get our activity suggestion. 🙂

browser extension example

The extension also displays the link details of the property as shown below.

browser extension example

Conclusion

In this article, we learned how to create a simple activity suggestion chrome extension.

We also learned how to run background activities in chrome extension, which calls a backend API and fetches the JSON response.

The code is available on Github.

How To Create A Simple Google Chrome Extension
Scroll to top

Discover more from ASB Notebook

Subscribe now to keep reading and get access to the full archive.

Continue reading