shopping24 tech blog

s is for shopping

February 21, 2014 / by Daniel Lucks / / @

Building a Chrome Extension

Today one of the most favorite browser used by web developers is Google Chrome. This browser not only provides very powerful developer tools. There are also a lot of useful extensions available in the Chrome Web Store - most of them developed by web developers as well. But wouldn’t it be nice to create your own extension? This tutorial will show you how to.

The Basics

Before start hacking, I want to give you a quick overview of what Chrome extensions are exactly.

It’s all about familiar technologies

One of the main ideas of Google is to make developing apps and extensions for Chrome as easy as possible. So building an extension only requires technologies every web developer is familiar with: HTML, CSS and JavaScript. If your extension should have an UI (like a popup showing some information), you have to build it using HTML and CSS - and yes, you may use all of the fancy CSS3 and HTML5 stuff! The main logic of the extension has to be implemented in JavaScript.

So, an extension is like a … common website!?

Yes, it is. Building an extension is like building a common website. The only difference is that an extension does not require an UI. You may develop some extension just made of one or more JavaScript files. You can see such extensions like some kind of invisible website running in the background of the browser.

The Chrome APIs

So, setting up an extension is quite easy. The next step is to implement some crazy stuff. You know what? Chrome is doing most of the work for you. It provides many APIs for accessing even more features. Local storage, cookies, bookmarks, downloads, history and so on. You just have to use them. There is a good Chrome API reference available online.

No more theory, please!

I think, one of the most promising concepts of learning is learning-by-doing. So, let’s start building our first Chrome extension.

The scenario

One of the most important SEO onsite optimizations are correct and meaningful h-tags. So, looking at the HTML source code of websites and searching for <h1>...</h1> is important - and annoying. What if there was a button in the browser which highlights the h1 tag of the current website just by clicking it? - That. Would. Be. Great!

Our task: We are going to develop an extension that adds a button to the browser bar. By clicking this button, all h1 tags of the current website will be surrounded with a red border.

Setup a manifest file

The first thing we have to do is to declare a manifest file. Create a file named manifest.json in the root directory of your project and open it. Then add the following content to it:

{
    "manifest_version": 2,
    "name": "My First Extension",
    "description": "Add some description...",
    "version": "0.0.0.1",
    "browser_action": {
        "default_icon": "icon.png"
    },
    "content_scripts": [{
        "js": ["content.js"],
        "matches": ["*://*/*"]
    }],
    "background": {
        "scripts": ["background.js"]
    },
    "permissions": ["tabs", "*://*/*"]
}

Like any other manifest, this file contains some meta information and configurations of the extension. Some of them are used by the extension itself, and some of them are important to publish it in the Chrome Web Store. It is just a simple data container formatted in JSON.

Here is a short explanation of all settings we need and set for our extension:

Parameter Description
manifest_version There is an older format for manifest files, but it is very recommended to use the new format. All you have to do is to set this parameter to 2.
name No explanation needed, I guess. ;-)
description This text will be used in the Web Store as a short teasing text to promote the extension.
version The version number of the extension. Every time you upload a new version into the Web Store, you have to increase this number.
browser_action This parameter is to set up the browser UI of extensions. We only want to add an icon to the browser bar. So, set the default_icon attribute to icons filename.
content_scripts All listed JavaScript files will be injected into websites whose URLs match the given pattern. In this case we use the most general pattern, so the content scripts will be injected into every website.
background With the scripts attribute of this setting we define a list of files that will be loaded and executed on every start up in the background of Google Chrome.
permissions The Chrome browser provides a lot of APIs. To be able to use them, you have to request for permission for each of them during the extension installation process. In this example we only use the tabs API. Like defining content scripts you have to give a URL pattern, too. The requested permissions are only valid to URLs matching this pattern.

The content script

In generall content scripts are JavaScript files that are injected into a website by an extension. Only in content script you may access the DOM of a website to modify or get some information from it. The extension itself - running in the background of the browser - is not able to access this DOM, but to execute functions of the injected scripts.

As defined in the manifest file, Chrome tries to inject a JavaScript file named content.js into websites, if our extension is installed and enabled. In this case this file will be injected into every website, because we set the wildcard matching pattern *://*/*. Maybe in another project you want a more specific pattern, like *://google.com/*. But in this case we don’t.

Now lets implement a function that finds all h1 tags in the current DOM and highlights them by adding a red border. Very easy job for all JavaScript ninjas:

var extension = {
    highlight_h1 : function () {
        // Find all h1 tags
        var tags = document.getElementsByTagName('h1');
        // Add a red border to each of them
        for (var i=0; i<tags.length; i++) {
            tags[i].style.border = '5px solid red';
        }
    }
};

Just add this code to a file named content.js in the root directory of your project. The next step is to execute the highlight_h1() function by clicking the extensions icon in the browser bar. To implement this, we need a so called background script.

The background script

A background script is a JavaScript file in the background of the browser executed on every Chrome startup. Our approach is to use such kind of file for adding a listener callback to the onClicked event of the extensions button in the browser bar. This callback invokes the function highlight_h1() of the content script which finally highlights the h1 tag of the current website.

chrome.browserAction.onClicked.addListener(function () {
    chrome.tabs.executeScript(null, { "code": "extension.highlight_h1()" });
});

As defined in the manifest, Chrome looks for a file named background.js. Create such a file in the project root and add the few lines of code to it.

In this file we use the tabs API. This API provides some useful functions to interact with the tabs of the browser. One of it is executeScript(), which executes a piece of given JavaScript code in any tab. The first expected parameter is the ID of the tab to use. Fortunately this parameter may be set to null to select the currently opened tab. The second parameter is some kind of parameter-object containing a bunch of settings. But we are only interested in setting the code attribute with some JavaScript code that invokes highlight_h1().

That’s it. We’re done! Now let’s install it.

Installing Chrome extension locally

Installing Chrome extension from the webstore is easy. Installing them from your local machine is even more easy. Just type chrome://extensions/ in the browser bar and the extensions overview will show up. You will find the Developer Mode checkbox in the upper right corner - check it! Now some additional buttons will appear at the top of the page. One of it is Load unpacked extension. Click it, select the project directory and confirm. Done. Now a new icon in your browser bar should appear. By clicking this icon, all h1 tags of the current page will be highlighted with a red border. Hooray!

Downloads

Source code of this example: Download