Building Google Chrome Extensions From Scratch – Part 3

By Ryan
Mar 20th, 2012
0 Comments
2234 Views
Building Google Chrome Extensions From Scratch

Building Google Chrome Extensions From Scratch

This is Part 3 of the series – Building Google Chrome Extensions From Scratch. In this part, we are gonna continue from where we left off in the previous part. As a quick recap, in Part 2, we covered
  • How to add a popup page to an extension.
  • How to add a background page to an extension.
  • How to communicate between extensions using the chrome extensions API.
In this part of the series, we will try to explore the other files that you are most likely to use when building a chrome extension.
[linkad]

Configuration

Google Chrome ExtensionWhen you have an extension, you may not want it to be active for all the web pages. You may instead want it to be active only for a particular website, or a URL pattern to be precise. In order to achieve that, chrome extensions give you two options. 
  1. Page Actions 
  2. Browser Actions 

You set up an extension as a page action, when you want the extension icon to be visible at the rightmost end of the address bar but only when it satisfies a particular condition. For instance, assume that you want the Mr0 icon to be visible only when we open a wikipedia page. A page action appears in the address bar of the browser instead of the toolbar. Lets try to make our extension a page action.

Here’s what our new manifest file would look like

manifest.json

{
  "name": "Mr0",
  "version": "1.0",
  "background_page": "background.html",
  "permissions": ["tabs"], //We will talk about this later
  "page_action": {    "default_icon": "images/icon19.jpg", "default_popup": "popup.html" }
}
In order to change the visibility of the extension icon, we would need find a means to be notified when the url in the tabs change, i.e. when the user selects a different tab. The listener would have to be placed in the background page because it is the only page in the extension that is alive in the browser all througout. Here’s what you could write in the extension page.

background.html

function checkForWikiUrl(tabId, changeInfo, tab) {
    // If the URL of the tab contains the string wikipedia.org
    var isWikiUrl =  tab.url.match(/wikipedia.org/);
    if (isWikiUrl) {
        // ... show Mr0.
       chrome.pageAction.show(tabId);
    }  else  {
       chrome.pageAction.hide(tabId);
    }
};
//Listen for any changes to the URL of any tab.
chrome.tabs.onUpdated.addListener(checkForWikiUrl);
The code is pretty simple. As you might have noticed in the previous snippet, we added a new key in the manifest file – “permissions“. This is necessary if you want to grant your extension access to the chrome tabs javascript extension API. If you don’t do that, your javascript code in the extension page for registering an handler for the onUpdated event will result in an error. 
Now if you reload your extension and you open a wiki page in the tab, you will observe that the extension icon appears in the address bar whenever you open a wikipedia page. If you open any other page, the extension icon will automatically disappear.
[linkad]

Browser Actions
‘Browser actions’ is what we have been using all along in all the previous parts of the series. When you set up an extension as a browser action, the extension icon will be visible in the toolbar, no matter what tab or what page you are on. All throughout the series, we have kept the Mr0 extension to have a browser action instead of a page action because I wanted to see the icon in the browser toolbar. However you may choose to do it differently depending upon your requirement. 
There is however a small difference between a browser action and a page action. If you have a browser action, you can add a badge to the extension. You cannot do the same for a page action. Wondering what a badge is? Well, a badge is nothing but tiny piece of text that you can display over your icon in the toolbar. You can do this in the background page for the extension by simply adding the following line of code
chrome.browserAction.setBadgeText({text:'Mr0'});

Content Scripts
Content scripts are the scripts that you specify in the manifest file, which get included on all the pages for which the extension is configured to run. For example, if you create a simple content script in your extension that logs a message such as ‘hi’ on the console of the web page, you will be able to see the message printed on each web page that the extension is configured to run on. Lets try it out with our Mr0 example.

In order to do this, all that you need to do is to create a simple javascript file and maybe call it myScript.js and place it directly under the root directory of your extension. We are just gonna add a simple line to it.
console.log("Bingo");
Now, in your manifest.mf file, you need to mention this script as a content script. Here’s how our manifest.mf would look like after the change
{
"name": "Mr0",
"version": "1.0",
"background_page": "background.html",
"permissions": ["tabs"],
"content_scripts": [
{
       "matches": ["http://*.wikipedia.org/*"],
"js": ["myScript.js"]
}
],
"page_action": {
"default_icon": "images/icon19.jpg",
      "default_popup": "popup.html"
  }
}
If you take a close look, you would have noticed that I had to use another property – “matches” inside the content_scripts array so that the content script will be injected only into the pages that match the given url pattern. There can be any match pattern and you can refer to the documentation here for more details.
Now when you open any wikipedia page, and you press F12(Shortcut to open the chrome developer tools frame), check out the console and you will observe a cool message that says “Bingo”. You can open any number of wikipedia pages, and the same message will be printed on the console of each of these pages.
What this actually indicates is that you can write custom javascript and execute it on each page independently. I used the word independently because your custom script will be executed such that although it will have access to the DOM structure of your page, it will not be able to access any other javascript that is executing on that page. This allows you to write your custom scripts without worrying about the clash of variable names.

Using the same feature, you can also include external libraries into your chrome extension. For example, you can add the jquery framework file into your extension. The version of jQuery that you make use of in your extension can be different from the version of jQuery being used by the client, and there wont be any clashes whatsoever.

You can add multiple content scripts separated by commas in the ‘js’ object. For example, the following piece of code will allow you to add the jQuery library into your extension and make it available for use in all your custom scripts.
"content_scripts": [
{
        "matches": ["http://*.wikipedia.org/*"],
        "js": ["jquery.js","myScript.js"]
    }
]

This code assumes that you have a file called ‘jquery.js’ directly under the root directory of your chrome extension.

Now that you have a javascript framework and the ability to access the DOM of a page via your content script, you can do pretty much anything that is possible with the DOM of your page with ease.
There are several other configuration parameters that will come in handy when you create your chrome extensions. However the examples in this series should be sufficient to get you up and running from scratch in no time.

Building Google Chrome Extensions From Scratch – Part 1

By Ryan
Feb 20th, 2012
2 Comments
2789 Views
Browser extensions have been all over the place lately. The past couple of days have been pretty amazing for me since began exploring these nifty little things. I learnt quite a bit, some out of sheer luck, some after a lot of trial and error and some after perusing the documentation a couple of times.  
Building Google Chrome Extensions From Scratch

Building Google Chrome Extensions From Scratch

In this series, I plan to cover the topic of creating browser extensions using Google Chrome which undoubtedly is my browser of preference. There are a lot of tiny little things that I will cover in this series, some of which were not as obvious to me at first.  
In the first part of this series, we will first understand what exactly is a chrome extension. And what are the most important basic components that you would need in order to make a Chrome extension from scratch. You can use this series as a step by step guide to create your first chrome extension. 

What Is Being Covered?

  • How to build Google Chrome extensions?
  • What do I need to learn in order to build a Google Chrome extension?
  • How to install my own extensions in Google Chrome?
  • How to use setup the icon for a Google Chrome extension?
[linkad]
So, What Exactly Is A Browser Extension?

Well, if you expect me to answer what a browser extension is, you’re in the wrong place buddy. However, just in order to give you a brief idea, a browser extension is nothing but a small piece of functionality that you can add to your browser, quite similar to the way you install applications on your personal computer/laptop/other devices. 

Why Google Chrome?

Because I like chrome (Yea, you guessed it right, I am -a bit- biased!)


Getting Started – What exactly makes a Chrome Extension  
An extension in google chrome is nothing but a web page.
Wait. Let that line sink in for a moment.
Whoa! What! An extension? Is a web page? You gotta be kidding me!
Fortunately/unfortunately (whatever way you’d like to think about it) I am not kidding. When I first realized that Google chrome extensions are nothing but web pages, and you don’t need to know any extra language other that javascript and css and html to build a chrome extension, my heart literally jumped with joy. If you are a fan of jQuery(like I am), you would be glad to know that you can use all the jQuery you wish in a google chrome extension. Why? Simply because its nothing but a web page!
Phew. I hope that relieves you a bit if you were holding back learning how to make extensions dreading the thought that you would need another new language in your arsenal. But then, there are a few caveats. Google chrome extensions are a some kind of special web pages. I say that they are special because these pages have access to the chrome extension javascript API. So, you can make use of all the javascript you know, but you would have to learn about a few functions that make an extension work like an extension. But then, don’t tell me you expected it to be a bed of roses either!
[linkad]

Getting Into The Nitty Gritty Of Things 
When you think of chrome extensions, think about 2 main things 
  • A file to describe your extension.
  • An hidden page that runs in the background – the exension’s background page.

There are of course many other pages and you can add a tonne of other stuff that you can do to make your extension all the more cool and fancy, but since this a is a step by step guide, I will be talking about each of these components one at a time as elaborately as my time (and mood) permits.


The Extension Descriptor File

I like to think of the descriptor file as the heart of a chrome extension. Without it, the browser would have no way of identifying your extension. Its like spiderman, it has great power and hence great responsibility too. Don’t worry, you don’t need to battle computer animated creatures to make our spiderman. In fact, its quite the opposite. If you have worked on javascript, I am pretty sure that you might have heard about JSON. It stands for JavaScript Object Notation. If you feel that I mentioned something out of your ken, you need to go back to google and first know what JSON is all about. Fear not, its pretty easy and will barely take you 5-10 mins to understand it. I had also written a post a couple of days ago where I discussed the difference between a JSON and JSONP, in case you are curious.  
Coming back to our heart/spiderman, the descriptor file has a predefined name – manifest.json and it contains nothing but a JSON object that describes your extension. As the bare minimum, you need to specify the name and the version of your extension. 

Creating Our First Extension. 

We need to think of a name to give our extension. Lets say, we call it “Mr 0”. Its not the letter O, its the numeral zero. So, our extension is Mr zero. Why the peculiar name “Mr 0”? Well, everything in programming starts with a 0, like array indexes and blah blah, and even we human beings started from a 0, a zygote, or an egg, or whatever!.  
First create a new folder, and call it, lets say chrome_ext and then create a manifest file with the name manifest.json in the newly created folder Now, we need to specify the name and the version of our extension in the manifest file using json. Here’s how we do it
{
    "name": "Mr0",
    "version": "1.0"
}
That is just about what you need in order to be able to install an extension into your google chrome browser. (Observe that the name of the extension is independent of the name of the folder which contains the extension files, which in our case is chrome_ext). In order to install an extension from your local drive, you need to open the extensions page in google chrome via the Settings(the wrench on the top right)-> Tools->Extensions. A browser window opens up enlisting all of your installed extensions if you have any.
Extensions that you download from the web store are in a available in a particular format – .crx files. Since you are simply installing an extension from a folder, you need to enable ‘developer mode‘ in your chrome extension list panel. So, click on the checkbox that says ‘Developer mode’ and 2 additional buttons appear on the screen as shown in the screenshot.
Load Unpacked Extensions
Click on the button that says ‘load unpacked extension‘ and browse to the folder ‘chrome_ext’ that we created earlier and click on ok. The moment you click on OK, the extension gets installed and you will be able to see your first chrome extension among the list of extensions installed. And hail, because Mr0 is just born!

Giving Our Extension A Face
Well, our newly born Mr0, is pretty dumb(as of now). In fact, he is absolutely useless. After all, how can he be of any use? He just has a name. In order to be able to seen by others, Mr0 needs a face. So lets give him a face. The face that we are going to give Mr0 is that of an Icon in the toolbar. In order to give Mr0 and icon, we need to specify the image for the icon in the manifest file. 
Icons in the chrome toolbar are not more than 19×19 pixels. If you use a larger image, it will simply be scaled down to fit this size. I am going to keep it pretty simple. I am just going to create a 19×19 pixel image using paint and give it a dark red color. Nothing fancy. You can use any image you wish. I am going to name my image “icon19.jpg” and I will place it in a folder called “images” under my chrome_ext directory.
Here’s how we can reference this image in the manifest file.

 

{
  "name": "Mr0",
  "version": "1.0",
  "browser_action": {
    "default_icon": "images/icon19.jpg"
  }
}
That was pretty simple, wasn’t it? We were quickly able to reference the image relative to the current file(the current file in this case being the manifest.json file).
Also notice that unlike the name and version attributes, the default_icon attribute is a nested attribute under the browser_action attribute. The browser action attribute is a map that contains key value pairs to describe different elements that are used to give the extension a user interface. 
Now, if you reload your extension, you will be able to see a little icon at the top in the chrome toolbar and if you hover your mouse over it, a small tooltip comes up which displays the name of your extension. In this case, it(proudly) shows Mr0 in the tooltip that appears. 
Our extension, Mr0 has a face now. Hurrah!
We haven’t done much till now. In fact we have barely scratched the surface. But as you will see in the next part of the series, we shall slowly build Mr0 and explore the many other files associated while building a chrome extension.

About the Author

- Ryan Sukale is a Software Developer by Profession and loved to write about elements of web design as a hobby. Although loves to dabble and experiment with various technologies, his special ares of interest include Java, jQuery, CSS, Graphic design and the new and revolutionary HTML5. You can read more of his technical articles and experiments at MyCodeFixes.

Leave a Reply to Building Google Chrome Extensions From Scratch - Part 2 - Idle Brains Cancel reply

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

facebook comments: