Translate

Wednesday, April 23, 2014

How To Write Basic Chrome Extensions

This may not be news to some people, but I was pleasantly surprised to discover recently that Chrome extensions are written primarily in JavaScript. This makes them incredibly easy to get into for someone like myself, and I'm sure for some of you folks who may be reading this.

There are some more complex things which can be done, which involve injecting CSS, and popping up background pages in response to specific browser events, and you can even configure a settings page, but for the purpose of this post, I we are just going to use simple JavaScript injection.

We are going to be creating a simple extension which will convert all images on a page into placehold.it images on the fly. If you haven't used placehold.it before, it is bascially a placeholder site where you supply you image dimensions in the URL, and it will generate a gray placeholder image. The dimensions of the placeholder images will be exactly equal to the original image's dimensions. So, without further ado, let's get started!


Getting Set Up

The first thing you will want to do is generate the extension's manifest file. We could write this out by hand, and generate the folder structure for our extension by ourselves, but we are not going to be doing that, because we will be used a service called Extensionizr to generate all of this for us!

When you visit Extensionizr, you will be greeted by a page whichs looks like this:



There are quite a few options on this page, but the first option we will click is Hidden Extension. This will set a radio button or two for us automatically. The settings we want can be seen in this image, however, I will go over each one which needs to be set for our basic extension.


Under Extension Type, we will want to choose Hidden extension. It should already be set to this.
Under Background Page, choose No Background.
Under Options Page, we will choose No options page.
Under Override, we will be choosing No Override.
Under Content Scripts, we will be selecting Inject js.
We do not need any Misc Addons, so leave this blank.

Now, we will skip over URL permissions and permissions, and click Download It.

You will receive a zip file with the skeleton of your extension in it. Extract this somewhere where you can find it later and maybe rename it to something more descriptive. I placed mine into a ChromeExtensions folder in my root directory, and called it SampleExtension.

Modifying the Manifest File

Now that we have our skeleton extension, we will start filling it out. Go into the extension which you extracted to your computer, and open the manifest.json file in your favorite text editor. I will be using NotePad++, but you can use anything from NotePad to Visual Studio Professional Edition. It doesn't matter as long as you are comfortable with it and it can open Json files.

The manifest.json file should look like this:


We are going to change the name, description, and matches. The name should be something like Imageify or just Sample Extension or something. The description can be anything you please. The matches field will be the sites on which your extension will inject the JavaScript code. We will just set it as <all_urls>. This will make the extension work on all sites.

Save this file and open up the inject.js file which is located in the src/inject/ folder. This is where we will write our actual code.

The JavaScript Injection


Our inject.js file will look like this to begin with.


We will want to place our code for our extension within the area where the console.log now resides. So get rid of the console.log line, and replace it with the following:

var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++) {
    var width = images[i].width,
        height = images[i].height;
    images[i].src="http://placehold.it/"+width+"x"+height;
};


Basically, all that this does is grab all of the image tags on the page and put them into an array. Then it loops through the array replacing the image's src attribute with "http://placehold.it/widthxheight". That's all.

Save this file and go back to your Chrome browser.

Installing Your Extension

In your URL bar type about://extensions. This will take you to Chrome's extensions manager. You will get a tab like this:


These are you extensions if you are unfamiliar with them. You will want to tick the little box in the upper right hand corner that says Developer mode. Click Load Unpacked Extension... and navigate to your extension's folder in the window that pops up. Click Ok, and if no problems occurred, your extension should appear at the top of the list.

Testing Your Extension

Now that your extension has been installed, point your browser to a site which has images, such as Google.com. If everything worked right, the images on the page should be replaced a split second after the page loads with placehold.it images.

I'm sure there are ways to speed this process up and make it so the human eye can not tell that the images are loading and then being replaced, however, for the purpose of this tutorial, this is fine.


Packing Your Extension

If at some point you are planning on sharing your extension with anybody, the best way would be to pack it up. To do this, go back to about://extensions in your Chrome browser. Make sure Developer mode is on, and click on Pack extension... Navigate to your extension folder again, and then click on Pack Extension. It will take just a moment, and then alert you that a *.crx file was generated. This is your extension. People just need to drag this file onto their Chrome browser in order to install it. A key file was also generated which is necessary to update your extension. Do not share this with other people.


Bonus Information

Chrome Extensions do not directly have access to a page's JavaScript variables and functions, presumably for security and general accident avoidance reasons. However, that does not mean that it isn't possible to modify page variables or call page functions from your extension. Just don't use it for evil. In order to access the page's 'view' of the code, you need to wrap your code in the following:

location.assign( "javascript:TYPECODEHERE;void(0)" );


As always, thanks for reading. I hope that this tutorial made sense and was easy to follow. Feel free to leave comments of all types! If you have made any Chrome extensions I would love to hear about them and check them out myself.

No comments:

Post a Comment