Creating an extension for Google Chrome

In this article I will try to tell and show by example how to write an extension for Google Chrome browser. We will touch on the main points of extension development, and more advanced mechanisms and functions are planned in future releases.

After studying this article you will be able to:

  1. Create a simple web browser extension;
  2. Work with the context menu of the browser;
  3. Work with the browser’s local storage.

Introduction

Not so long ago, for one of my projects I needed to write a firmware that would perform the actions I needed automatically. I had a choice between a Visual Basic program or web development, and I chose to develop an extension for Google Chrome. For those Internet users who don’t know what an “extension” is.

Extensions – are additional features that are easily plugged into Google Chrome. Third-party extensions allow you to plug the features you want into your Google Chrome web browser for developers and other IT professionals, avoiding the ones you don’t need.

The main advantage of extensions is that they run directly from the browser environment, and this makes them easier to use. Also, I would like to understand extensions in more detail, since there is no documentation for novice developers, and there is not much useful content on the Internet. In this article, I’m going to touch on one of the features when creating an extension – an image gallery. Let’s say we found an interesting picture and saved it, but it got lost in an infinite number of folders. It’s even easier to get all the saved images in one click instead of searching through folders.

The principle of the extension will be as follows:

  1. Clicking on the image will bring up a context menu with our “Add to Gallery” feature;
  2. Clicking on the extension icon (near the address bar) will open the gallery;
  3. In the gallery you will be able to delete unwanted images.

Extension structure

The file organization of our Google Chrome extension will be as follows – html pages, JavaScript functions, css styles, and manifest.json configuration.

Notice: manifest.json is a plain text document, but it will contain the basic configuration of the extension, and it is advisable to save it in UTF-8 format.

First, let’s talk about the architecture of the extension, which conditionally divides it into two parts: 

  • something that works in the context of the page being viewed;
  • what works in the context of the browser. 

The communication between them is done through messages. Looking ahead, we will use the background page to add our function to the image context menu.

In manifest.json we specify the following data:

  • The name of our extension;
  • Permissions in access;
  • The icon of the plugin, as without it;
  • The conditional version of the project;
  • Other necessary information about the project. 

You should be careful with the quotes in this file, because if even one character is missing, the extension will not install.

The important parameters for us are background_page and default_popup – the background and popup window. It will appear when you click on the extension icon in the address bar of the page you are viewing. Unlike the default_popup page, which runs when you click on the extension’s icon, the background_page only runs once when you start the browser or extension. In the permissions we’ll specify working with the context menu, tabs, unlimited local storage, and permission to access any address. 

For those users who don’t know:

Local storage — is an internal database that resides on the client side and stores key pairs and their values. This database data is stored on your computer in the browser. Each browser has its own local storage on your computer.

The entire source code of the manifest.json file configuration:

{

   “background_page”: “background.html”,

   “description”: “Image Gallery”,

   “icons”: {

      “16”: “search-s.png”,

      “48”: “search-m.png”

   },

   “name”: ” Gallery”,

   “permissions”: [ “contextMenus” , “tabs”, “http://*/*” , “https://*/*”,”unlimitedStorage”],

   “version”: “1”,

    “browser_action”: {

     “default_title”: ” Gallery”,

     “default_icon”: “search-m.png”,

      “popup”: “popup.html”

    }

}

Please note!

The parameters given in the example above are the standard base configuration without any trickery. There are other parameters, but we don’t need them yet. The allowable size of the icons should be in the following formats: 16*16, 48*48.

Extension installation

To install an extension by opening a file, we need to package our extension, I will tell you about this at the end of the article, because after packaging it is no longer possible to add or change anything in the extension. All files of our extension will be in the same folder. Therefore, the installation will be a little more than opening a file:

  1. Click on the “Google Chrome Settings and Management” button;
  2. From the context menu that appears, select “Settings”;
  3. Select “Extensions” in the menu that appears;
  4. Click on the checkbox labeled “Developer Mode” and then “Download unpacked extension”;
  5. Select the folder with our extension and click “Ok” or “Start”.

If you get an error, then most likely you made a mistake in the file manifest.json and the error window should indicate the line in the file containing the error. Further on in the article we will add new files and write code to them. The extension should “update” automatically, if it doesn’t, please reload the browser.

Interior gallery design

To avoid writing the gallery yourself, you can download a ready-made version, thankfully, there are many available beautiful jQuery libraries with galleries, which you can find by Google search. I downloaded a ready-made version from smoothgallery.jondesign.net. It’s a free gallery that uses jQuery and we can add and modify it. Great, we can work with it safely. After downloading it, I unzipped it and removed all the example files and images to them except demo.html. Now we can move the files to the folder with our extension.

File background.html

As we already said, this is the background page, so let’s write in it the javascript code for adding the function to the image’s context menu:

chrome.contextMenus.create({“title”: “Add to gallery”, “contexts”: [“image”], “onclick”: addImage});

Extension structure

When you click, the addImage function will be executed, which will save the URL of the image. We will create local storages chimggali0, chimggali1 , chimggali2, etc.

0, 1, 2 … N – links to the saved images, where N is the last link.

We will also get and store the date when the user saved the image. The local storages for the date are chdate0, chdate1, chdate2 and so on. We make a local repository for the i variable, which is responsible for numbering images. 

If the local storage does not exist, then i=0, otherwise we assign a value from the storage. After execution of the function i is incremented by 1 and stored in the repository.

Our function code:

function addImage(info,tab) {

if ( ! localStorage[‘chgali’])

{

i = 0;

} else {

i = readProperty(“chgali”); }

imggal = info.srcUrl;

   localStorage[“chimggali”+i+””]=imggal ;

   var currentTime = new Date()

   var month = currentTime.getMonth() + 1

   var day = currentTime.getDate()

   var year = currentTime.getFullYear()

   var fordate = day+ “.” + month + “.” + year;

   localStorage[“chdate”+i+””]=fordate;

   i++;

localStorage[“chgali”]=i ;

}

To get the value of the “Cell” I used the readProperty function for convenience. I will continue to use this function.

ReadProperty function code:

function readProperty(property, defValue)

{

if(localStorage[property] == null)

{

return defValue;

}

return localStorage[property];

}

File demo.html

This is the file of our gallery, when you enter it, you will see the added images. If you immediately open this file, it will contain the standard images added by the author using HTML. We need to generate them dynamically. The first thing you need to do is to remove the static images. We remove all the <div class=”imageElement”> and the code in them. If you open this file now there will be nothing in the gallery, so you have to write some JavaScript code to display the added images.

The function will be called load and will be executed when the page loads. In this function we take the value of chgali from the local repository and create a loop. In this loop we create div container with id=”imageElement”, that contains the image. We get the values of the link to the image and the date it was added, in the h3 tag will be the date and in the tag will be a link to the image. Using the innerHTML we add our container to the div container with id=”myGallery”.

Now you can start the gallery by adding window.addEvent(‘domready’,startGallery); at the end of the function. If you don’t like the proportions in which the add date and URL of the page are displayed, you can experiment with the jd.gallery.css file in the css folder. It’s where the styles of all of our gallery elements are written and after spending a little time, you can pick the perfect values to your liking. 

One problem solved, the gallery already has images added, but they can’t be deleted. To be able to delete them, we will create an idelete function with the image number as an argument. The function will loop overwrites the corresponding “cell” in the local storage to the next, until it reaches the last one, and reduces chgali (the number of all images) by 1. The same should be done with the date of adding an image. At the end write reload the tab.

Code of idelete function

var func = function idelete(asd) {

   for(var f=asd;f<team-1;f++) {

      var fgh=f+1;

      var rty = readProperty(“chimggali”+fgh+””);

      localStorage[“chimggali”+f+””]=rty;

      var rtu = readProperty(“chdate”+fgh+””);

      localStorage[“chdate”+f+””] = rtu;

   }

   var close=readProperty(“chgali”);

   localStorage[“chgali”] = close-1;

   window.location.reload();

}

Please note!

Team-1 is the number of images.

We write code in the load function that gets the number of thumbnails. We create a loop that adds a small cross in the corner to remove each thumbnail. Let’s add an event: when you click on the little cross, perform idelete function with an argument – the order number of the thumbnail.

Example function code:

var close = document.getElementsByClassName(‘thumbnail’);

   for(var t=0;t<close.length;t++) {

   close[t].innerHTML='<img src=”http://www.upyourfiles.com/templates/default/images/x.gif” id=”cl’+t+'” onclick=”func(‘+t+’)”>’;

}

File popup.html

There are two ways to do this. Since we just have to open the gallery, we can avoid using a popup and when you click on the icon, it will open the gallery immediately. Otherwise a window with a “Gallery” button will appear.

The first option – Without a modal Pop-up window

If you use this option, you must remove the “popup” line from the “manifest.json” file: “popup.html”.

Write in the file background.html

chrome.browserAction.onClicked.addListener (function() {

  chrome.tabs.create({“url”:”demo.html”});

}

Please note! 

chrome.browserAction.onClicked excludes modal windows and vice versa. With this code we open a new tab with the gallery when we click on the icon.

The second option – Use a Pop-up window

In the file “popup.html” we create a button and perform the function “click” when clicked. To create beautiful buttons using CSS styles, you can use these online style generators:

A list of resources for your reference:

In the click function, let’s write the creation of a new tab with the gallery:

chrome.tabs.create({“url”:”demo.html”});

Packing the created extension

  1. Click on the button “Google Chrome Settings and Management”;
  2. A drop-down list should appear in it select “Settings”;
  3. Select “Extensions” in the menu;
  4. Tick the checkbox to confirm the activation of “Developer Mode”, and then click on “Packing Extension”;
  5. In the field “Extension Root Directory” select the folder with the extension. Leave the additional field empty.
  6. The window that appears shows the location of the packed extension and the keys file. You will need the keys file to install updates of the extension, not its copies. When packing a new version of the extension, just specify the keys file in the second field when packing.

Please note! 

Although the packaged extension has the extension “CRX”, but it is a normal zip-archive of the specified folder with the addition of a unique identifier.

After all the successful manipulation you can now distribute your first extension for the popular web browser.

Conclusion of an article on creating an extension

Designing and writing extensions for a popular browser is actually quite a fun process. In the next article in the Google Chrome extension development series, I’ll cover topics such as the Chrome API, XMLHttpRequest, and regular expressions.