How to create Chrome Extensions?

Reading Time: 4 minutes

Chrome Extension is a very useful tool to automate your tasks. There are a lot of chrome extensions available that you can use very easily. The most important and interesting thing is you can create your own extensions. In this blog post, I’ll show you how to make a Chrome extension to help you innovate your tasks and get back to productive work. Google Chrome extensions are programs you can install in your Chrome browser to change its functionality. Chrome extensions are built with HTML, JavaScript, and CSS scripts and are essentially small websites uploaded to the Chrome store.

The only difference between a Chrome extension and a regular website is that extensions contain a manifest file, which gives them a specific function to execute. Few examples of available chrome extensions in chrome store are Grammarly, Buzzsumo, Google Docs Offline etc.

Let’s get Started

First of all you have to create a project folder in which you will put all your files related to chrome extensions. This is important because, for Chrome to load your plugin, it needs to be pointed towards a folder containing your extension files.

Make your extention manifest file

All Chrome extensions require a manifest file. The Manifest file tells Chrome everything it needs to know to properly load up the extension in Chrome. So we’ll create a manifest.json file and put it into the folder we created. You can leave the manifest file blank for now. his serves a similar purpose to a package.json, it provides the Chrome Web Store with critical information about the project, including the name, version, the required permissions, and so forth.

{
  "name": "To Do List",
  "version": "0.01",
  "description": "A simple pop out todo list",
	"browser_action": {
		"default_title": "Epic Mode",
		"default_popup": "popout.html",
        "default_icon": "to-do-list.png"
	},
  "icons": {
    "128": "to-do-list.png"
  },
  "manifest_version": 2
}

Name basically tells the name of your app, Version tells the version , since its our first version so we have named it as 0.01. Description is basically few line description about your project. Background scripts, like many other important components, must be registered in the manifest. Registering a background script in the manifest tells the extension which file to reference, and how that file should behave.

You can add your icons in the same project directory , they can be added using icons and default icons keyword in manifest file.

Load Your Extension into Chrome and Check for Errors

Now it’s time to test your extension to make sure Chrome will run it.

Follow these steps:

  1. Go to chrome://extensions in your Google Chrome browser
  2. Check the Developer mode checkbox in the top right-hand corner
  3. Click “Load Unpacked” to see a file-selection dialog
  4. Select your extension directory

If your extension is valid, it should load immediately.

Otherwise, you will see an error message at the top of your page. If this is the case, look for errors, correct them, and try loading your extension again.

The most common errors people make here are syntax errors. Double-check all of your commas and brackets and make sure they are formatted correctly.

Creating the UI

The next step is to create the user interface that our Browser Action will display when it is clicked.

Open up the popup.html page and add the following:

<!DOCTYPE html>
  <head>
    <meta charset="utf-8">
    <title>Todo List</title>
    <style>
    body{width:300px;}
    .todo-items,
    .todo-items li{
      margin:0;
      padding:0;
      list-style: none;
    }
    .todo-items li{
      padding:10px;
      border-bottom: 2px solid grey;
      display:flex;
      justify-content: space-between;
    }
    .todo-items li:hover{
      background:rgba(0,0,0,0.25);
    }
    .todo-items li.done .item{
      text-decoration: line-through;
    }
    .todo-items div span{
      margin:5px;
      font-size:1em;
      cursor: pointer;
    }
    .new-item{
      display:none;
    }
    .create-todo{
    margin-bottom:10px
    }
    h1{
    color: grey;
    font-family: poppins;
    }
    </style>
  </head>
  <body>
    <h1>Let's Do This!!!</h1>

    <button class="create-todo">New Item</button>
    <div class="new-item">
      <input type="text"/>
      <button>Save</button>
    </div>

    <ul class="todo-items">
    </ul>

    http://popout.js
  </body>
</html>

Lets implement the logic with popup.js

Open up the popup.js file and add the following code:

document.querySelector('.create-todo').addEventListener('click',function(){
  document.querySelector('.new-item').style.display='block';
});

document.querySelector('.new-item button').addEventListener('click',function(){
  var itemName = document.querySelector('.new-item input').value;
  if(itemName != ''){

    var itemsStorage = localStorage.getItem('todo-items');
    var itemsArr = JSON.parse(itemsStorage);
    itemsArr = itemsArr || [];
    itemsArr.push({"item":itemName, "status":0});
    saveItems(itemsArr);
    fetchItems();
    document.querySelector('.new-item input').value='';
    document.querySelector('.new-item').style.display='none';
  }
});

function fetchItems(){

  const itemsList = document.querySelector('ul.todo-items');
  itemsList.innerHTML = '';
  var newItemHTML = '';
  try{
    var itemsStorage = localStorage.getItem('todo-items');
    var itemsArr = JSON.parse(itemsStorage);

    for (var i = 0; i < itemsArr.length; i++) {
      var status = '';
      if(itemsArr[i].status == 1){
        status = 'class="done"';
      }
      newItemHTML += `<li data-itemindex="${i}" ${status}>
      <span class="item">${itemsArr[i].item}</span>
      <div><span class="itemComplete">✅</span><span class="itemDelete">🗑</span></div>
      </li>`;
    }
itemsList.innerHTML = newItemHTML;

    var itemsListUL = document.querySelectorAll('ul li');
    for (var i = 0; i < itemsListUL.length; i++) {
      itemsListUL[i].querySelector('.itemComplete').addEventListener('click', function(){
        //
        var index = this.parentNode.parentNode.dataset.itemindex;
        itemComplete(index);
      });
      itemsListUL[i].querySelector('.itemDelete').addEventListener('click', function(){
        //
        var index = this.parentNode.parentNode.dataset.itemindex;
        itemDelete(index);
      });
    }
  }catch(e){
    //.
    //create a deafut item list..
  }

}
function itemComplete(index){

    var itemsStorage = localStorage.getItem('todo-items');
    var itemsArr = JSON.parse(itemsStorage);

    itemsArr[index].status = 1;

    saveItems(itemsArr);

    document.querySelector('ul.todo-items li[data-itemindex="'+index+'"]').className='done';

}
function itemDelete(index){

    var itemsStorage = localStorage.getItem('todo-items');
    var itemsArr = JSON.parse(itemsStorage);

    itemsArr.splice(index, 1);

    saveItems(itemsArr);

    document.querySelector('ul.todo-items li[data-itemindex="'+index+'"]').remove();

}

function saveItems(obj){

  var string = JSON.stringify(obj);

  localStorage.setItem('todo-items', string);

}


fetchItems();

You can change the logic according to your need and requirement. Moreover, this is just a sample code for simple extension. For more details visit the official website for chrome extensions.

Test the extension

It’s important to continuously test your extension to ensure everything works.

Test it out yourself, or have someone else test it.

If you have another person test it, do it without giving them instructions to make sure it’s intuitive to use.

At last, make changes as needed, then test your extension again. This is it for this blog. For more such blogs visit Knoldus Blogs Happy learning.

Written by 

Saumya is a Software Consultant at Knoldus Software LLP. She has done B.Tech from Quantum School of Technology, Roorkee. She has good knowledge of Devops technologies like Ansible, Terraform, Docker, Concourse, Jenkins, Kubernetes. She is very enthusiastic and energetic. Apart from technology, she is interested in various sports.

Discover more from Knoldus Blogs

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

Continue reading