Browser Applications – Chrome Extension Programming

We create open-source because we love it, and we share our finding so everyone else can benefit as well.

Browser Applications – Chrome Extension Programming

At first glance, one would imagine there is a lot to be known to write a chrome extension. The reality is that creating such a tool is quite easy, that is, once you understand the concept of the extension system. Let me show you why I enjoy this medium for quick monitoring apps, and what you need to create your own.

The Moving Parts of a Chrome Extension

Let’s start by looking at the anatomy of the Chrome extension. You will find that the entire app is written in JavaScript, using different JS scripts depending on the job.

background scripts: the backgrond script is the main process script for your extension, offering an “always-on” scripts, where you can run intervals*, and save and retain your state.

content scripts: when you need the ability to alter to update the DOM in the active tab, a content script is the only way to give your extension the ability to interact with the active tab.

popup scripts: clicking the extension icon may sometime provide a popup window, and this script works in tandem with a popup.html file.

options: when you right-click the icon of the extension, and choose the options, the html file you provide is what shows.

preferences: Just like the options window, you also have the preferences options which you also create and provide. This is accessible from the extension installation information.

The Chrome Extension Manifest

By default extensions do you allow you to use anything and everything, so you need to pick and choose the different options available. You set these options uses the manifest.json file in the root of the loaded extension. Here’s an example of this file:

{
  "name": "Test Extension",
  "version": "1.0.0",
  "default_locale": "en",
  "description": "an example extension manifest",
  "permissions": [
    "background",
    "notifications",
    "storage"
  ],
  "background": {
    "scripts": [
      "preferences.js",
      "background.js"
    ],
    "persistent": true
  },
  "web_accessible_resources": [
   "words.json"
  ],
  "options_page": "options.html",
  "options_ui": {
    "chrome_style": true,
    "page": "options.html"
  },
  "browser_action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "images/icon_16.png",
      "32": "images/icon_32.png",
      "48": "images/icon_48.png",
      "128": "images/icon_128.png"
    }
  },
  "icons": {
    "16": "images/icon_16.png",
    "32": "images/icon_32.png",
    "48": "images/icon_48.png",
    "128": "images/icon_128.png"
  },
  "manifest_version": 2
}

Just to give a quick rundown, the manifest is telling the extension which scripts to load, to enable background processing, notifications, and local storage. It also shows where the icons are, and to enable the popup and options menus. It’s also good to note, that when you publish an extension to the chrome web store, you will need to explain the need for each permission you enable before it’s reviewed.

Here are the other manifest options available:

Chrome Manifest Options

Programming Syntax

Chrome extensions are written using JavaScript, with some limitations to the syntax. I have made it a habit to write my abstractions in ES5, with some ES6 sugar sprinkled all over. Once you get your extension to a working state, it will be easy to notice when ES6 sugar breaks something. If you don’t want to deal with this, you can always use a bundler for your extension scripts. If you’re new to JavaScript, we wrote an article covering how you can learn JavaScript Efficiently and Effectively.

Extension Background Interval Timing

The interval timing of the background process can be quite inaccurate. One way to combat this is to create your own timer using a setInterval set for 5-10 seconds, to check the current time before executing the method you need run at a specific time. You can see an example of this in the following project’s background script:

Word Randomizer Extension

Talking Between Scripts (Message Passing)

Chances are you’ll want your extension’s scripts to have the ability to talk with each other. To do so, you need to use a background script to retain state, and act as a relay. Your other scripts will contact the background process, requesting data, and getting it back on the reply. You can see this in the extension linked above, starting with the background relay:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    var word = undefined;
    if(request.name === 'get-word') {
      word = WordList.word;
      wordSet = WordList.wordSet;

      chrome.runtime.sendMessage({
          action: 'update-word',
          word: word,
          wordSet: wordSet
      });
    }
  })

Front-end scripts like the content script, or in this case, the popup script, sends a message to trigger this:

chrome.runtime.sendMessage({ name: 'get-word' }, function(response) {});

When the response is send back, the pop has a listener for the reply here:

chrome.runtime.onMessage.addListener(function(message) {
    if ('action' in message && message.action == 'update-word') {
      if (Object.keys(message).includes('word')) {
        word = message.word;
        wordSet = message.wordSet;
        currentWord = message.wordSet.length - 1;
        createBlock();
      }
    }
  })

In each case we’re simply sending an object to each script, which can be changed to hold whatever we want, allowing the ability to send whatever you want.

Finding More Extension Examples

If you get stuck on a specific concept of Chrome extensions, the best place to clear that confusion up is the sample extension library. Here you can find example apps for every single extension use:

Chrome Sample Extension Library

While there is a lot available through the API itself, there isn’t too much more to the overall idea of write an extension. Most importantly, it’s incredibly powerful, giving you the ability to write whatever you want for your browser.

 

No Comments

Add your comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.