How to create a Chrome extension

How to create a Chrome extension

chrome extension

Overview

A browser extension is a small software module for customizing a web-browser. Browsers usually provide a store with both free and paid extensions. In case of a Chrome Browser, they can be found in Chrome Web Store. The variety of existing extension covers almost everything. If it doesn’t fit all your needs, you’re free to create a Chrome extension yourself.
This is exactly what we’re going to accomplish in this article – define an idea and create a Chrome extension to implement it.

An idea for a Chrome extension

Let’s imagine a situation when a user is surfing the internet. If he finds something really interesting but doesn’t have time to explore it deeper, then he’s either looking for a notepad or some application to make a note.
We suggest creating a Chrome extension that allows you to easily save an interesting piece of information with a link to revisit it just in 2 clicks.

Create the extension

Extension manifest

Extensions are made of different components such as background scripts, content scripts, an options page.

Every extension has a manifest file in JSON format. It contains the following important information:

  • Extension name, description, version, icons
  • Extension permissions
  • Background scripts
  • Content scripts
  • etc.

Let’s create a manifest file for our extension:

{
   "name": "Revisit Site Extension",
   "version": "1.0",
   "description": "Extension to save interesting pieces of site information to revisit later.",
   "permissions": ["activeTab", "storage", "/revisitLink"],
   "browser_action": {
      "default_popup": "popup.html"
    },
   "manifest_version": 2
 }

In permissions it requests access to:

  • active tab (to get a current URL)
  • storage (to store the last added link to revisit in browser local storage)
  • “/revisitLink” URL (to allow AJAX request to an external server)

browser_action.default_popup specifies an HTML file used for rendering a popup when the extension is activated.

Extension popup

Let’s have a look at the popup.html that represents extension popup:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="/lib/bootstrap.min.css" />
        <script src="/lib/jquery.min.js"></script>
        <script src="popup.js"></script>
    </head>
    <body style="background-color: #f4f1fd;">
      <div style="width: 520px;padding: 2rem;">
        <h1 style="text-align: center;color:#7272f3;font-weight: bold;">
          Revisit Site Extension
        </h1>

        <h4 style="text-align: center;color: #3072ec;">
          Save an interesting piece of information to revisit it later.
        </h4>

        <hr>

        <div id="successStatus" class="alert alert-success" role="alert" style="display:none;">
          The information to revisit has been successfully saved!
        </div>
        <div id="errorStatus" class="alert alert-danger" role="alert" style="display:none;">

        </div>

        <div style="display: flex;align-items: baseline;">
            <label for="" style="width: 100px;">URL</label>
            <textarea id="url" type="text" name="url" style="width: 300px;height: 150px;" readonly="readonly"></textarea>
        </div>

        <div style="display: flex;align-items: center;margin-top:1rem;">
          <label for="" style="width: 100px;">Information</label>
          <textarea id="info" type="text" name="info" style="height: 150px;width: 300px;"></textarea>
        </div>

        <hr>

        <h4>The Last Added</h4>
        <div id="lastAdded"></div>

        <div style="margin-top: 1rem;display: flex;justify-content: space-evenly;">
          <button id="cancelBtn" class="btn btn-secondary">Cancel</button>
          <button id="addBtn" class="btn btn-primary">Add</button>
        </div>
      </div>
    </body>
</html>

As you can see we load jQuery lib that we put into extension folder and popup.js with our custom logic.

        <script src="/lib/jquery.min.js"></script>
        <script src="popup.js"></script>

The rest is just to put the current URL and selected text to be sent to an external server.

Let’s have a look at popup.js:

chrome.tabs.executeScript( {
    code: "window.getSelection().toString();"
}, function(selection) {

    chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
        var url = new URL(tabs[0].url).href;
        document.getElementById("url").value = url;
    });

    document.getElementById("info").value = selection[0];

    chrome.storage.sync.get("lastAdded",function(res) {
      if (res.lastAdded) {
        document.getElementById("lastAdded").innerHTML = res.lastAdded;
      }
    });

});

$(document).ready(function() {

  $('#addBtn').click(function(){
    var url = $('#url').val();
    var lastAdded = '<a href="' + url + '">' + url + '</a>' + ' :<br>' + $('#info').val();

    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "https://localhost:8443/revisitLink",
        data: JSON.stringify({
          url: $('#url').val(),
          info: $('#info').val()
          // token: token
        }),
        dataType: 'json',
        success: function (data) {
          var url = $('#url').val();
          var lastAdded = '<a href="' + url + '">' + url + '</a>' + ' :<br>' + $('#info').val();

          chrome.storage.sync.set({ "lastAdded": lastAdded}, function() {
            $('#url').val(null);
            $('#info').val(null);

            $('#successStatus').css('display', 'block');
            setTimeout(function() {
              $('#successStatus').css('display', 'none');
            }, 3000);
          });
        },
        error: function (e) {
            console.log(e);
        }
    });
  });

  $('#cancelBtn').click(function(){
    window.close();
  });
});

Using chrome.tabs.executeScript we execute the code to get the current text selection. It’s set to “Information” field later.

To get access to a current URL, chrome.tabs.query is used.

In order to access browser local storage, chrome.storage.sync.get and chrome.storage.sync.set are used. Here it’s used mostly for demonstrational purposes saving and showing the last saved item to revisit.

As you can see, when “Add” button is clicked, an AJAX request is sent to an external server (not covered in the article).
As you may notice, there is a commented line with token as a parameter. If a server supports multiple users, then we would need to identify the existing session somehow. It could be done via setting a token being sent with every request.

How to install extension

If you want to install a Chrome extension locally, you should go to

chrome://extensions

and click Load Unpacked and select a folder with your extension.

As a result, you’ll see your extension in the list:

chrome extension

If you want to publish your extension to a store, you need to register a developer account (costs 5$).

Try our Chrome extension

After our extension is successfully installed, let’s open some web page and select a part of the text we’d like to revisit later. Then click on the extension icon to activate it and you’ll see the following:

chrome extension

After clicking ‘Add’ a request will be sent to an external server. The server itself is not covered in this article, so you’re free to add there any logic you want. The only thing we’ll show is that request is actually being sent:

chrome extension xhr

Conclusions

In this article, we’ve covered how to create a basic Chrome extension. Here we’ve worked only with popup-related functionality, but it’s just a tiny part of what’s available for a Chrome extension developer. So, if you like creating browser extensions, you should visit the official documentation and dive into this area.

Leave a Reply

Your email address will not be published. Required fields are marked *