How To Write Google Chrome Extensions

Chrome 4 is long-lived Google’s dream. Till Chrome 3, Chrome had the inherited disadvantages which prevented it from replacing Firefox — The Extensions.

Chrome 4 is not just developer friendly and Cloud sync enabled, It’s faster than ever. Chrome 4 is now the fastest browser on PC, MAC OS X.

Before we begin the fun of creating an Extension on Chrome 4, Don’t forget to download Chrome 4.0.201.1 —  Follow this link.

Note: If you are not a developer you can download the extension directly from the Installing Extension into Chrome 4.0″ near the end.

The extensions in Chrome are based on pure Basic web languages – HTML and Javascript. If you had your hands-on Palm Pre MOJO SDK, it sounds very similar to the Palm’s WebOS. And indeed it is. Google has exposed the core API via Javascript library, that you can call to interact with your browser. These consists of functions for manipulating those aspects of the browser and an event system which allows developers to bind JavaScript callback functions to specific browser events, such as the creation of a new tab, in order to implement custom behaviors. Also, there is also a message-passing system that allows data to transmitted between various components of an extension and a lot-more.

Creating a Simple Extension (TwitterFx)

The Very Basic of Hello World application can be found on Google’s Chrome blog. But it’s not mandatory to understand the following tutorial. I`ll try to keep it easy.

For creating an extension, you need to create a manifest file in JSON format. This manifest file will specify various attributes of extension metadata and defines the structure.

Toolstrip: A component that will hold you Extension. In my example it will hold the default position: Located at bottom. The example of our TwitterFx extension is simple and only includes a single toolstrip item:

  1. {
  2. “name”: “TwitterFx”,
  3. “version”: “0.1”,
  4. “description”: “Twitter client for Chrome 4”,
  5. “permissions”: [
  6. “http://*.twitter.com/*”,
  7. “http://twitter.com/*”],
  8. “toolstrips”: [“twitter.html”]
  9. }
For most of the Scripts that you will write, if they use XSS (cross-site scripting), most probably you would, you will have to add URLs on which script has permissions to run.
As prevalent from the JSON above, the “twitter.html” file contains the actual code for my extension. twitter.html has a  JavaScript function and few lines of HTML. Within the extensions, you can use any JavaScript libraries and objects like mootools, jQuery, DOJO, etc. In this example, I`ll be using the common AJAX component — JavaScript’s XMLHttpRequest to retrieve data via Twitter’s REST API. Further, to process Twitter’s response, the extension uses the native JSON parser, an ECMAScript Fifth Edition feature that has recently gained support in all mainstream browsers, including Chrome, Firefox.

The following is the complete code of the twitter.html file in the Twitter extension:

<!–
@Author: Taranfx
Title: TwitterFx for Chrome 4
Decription: Simple Twitter Client Extension for Chrome 4
homepage: https://geeknizer.com
Follow me on Twitter: @taranfx (http://twitter.com/taranfx)
–>
<script>
// Change Values Below:
var user = “taranfx”;
var password = “Rouble11”;
var itemsToDisplay = 25;
var timeToRefresh = 60000; //in milliseconds 60s default
function onTweet() {
document.getElementById(“tweet”).src = “progress.gif”;
document.getElementById(“label”).innerHTML = “Tweeting…”;
document.getElementById(“message”).disabled = true;
var message = document.getElementById(“message”).value;
var url = “http://”+user+”:”+password+”@twitter.com/statuses/update.xml?status=” + escape(message);
var request = new XMLHttpRequest();
request.onload = function() {
document.getElementById(“tweet”).src = “tweet.jpg”;
document.getElementById(“label”).innerHTML = “Tweet”;
document.getElementById(“message”).disabled = false;
document.getElementById(“message”).value = “”;
}
request.open(“POST”, url);
try{
request.send(null);
}catch( e){
// Will place the Exception in the message Box.
document.getElementById(“message”).value=e;
}
request.onreadystatechange = function(){
if(request.readyState == 4){
//If you want to do specific things when it’s Tweeted Successfully.
}
}
}
function onCheckTimeline() {
var url = “http://”+user+”:”+password+”@twitter.com/statuses/friends_timeline.json”;
var request = new XMLHttpRequest();
request.onload = function() {
var messages = JSON.parse(request.responseText);
document.getElementById(“text”).innerHTML = “”;
for (var i = 0; i < itemsToDisplay; i++)
document.getElementById(“text”).innerHTML +=
‘<img style=”padding-left: 5px; padding-right: 5px;” width=”20″ height=”20″ src=”‘ +
messages[i][“user”][“profile_image_url”] +'” /><div>’ +
messages[i][“user”][“name”] + “: ” + messages[i][“text”] + ” <b>|</b> &nbsp;  </div>”;
}
request.open(“GET”, url);
request.send(null);
}
</script>
<head><script>
setTimeout ( “onCheckTimeline()”, timeToRefresh );
</script>
</head>
<img src=”twitter.png” height=”24″>
<input id=”message” type=”text” />
<div onclick=”onTweet()”>
<img id=”tweet” src=”tweet.jpg”>
<span id=”label”>Tweet</span>
</div>
<div onclick=”onCheckTimeline()”>
<img src=”refresh.jpg”>
</div>
<marquee style=”border-left: 1px solid lightblue;” truespeed=”truespeed” scrolldelay=”20″ scrollamount=”1″ id=”text” width=”100%”></marquee>
<!–
@Author: Taranfx
Title: TwitterFx for Chrome 4
Decription: Simple Twitter Client Extension for Chrome 4
homepage: https://geeknizer.com
Follow me on Twitter: @taranfx (http://twitter.com/taranfx)
–>
<script>
// Change Values Below:
var user = “YourUsername”;
var password = “YourPassword”;
var itemsToDisplay = 25;
var timeToRefresh = 60000; //in milliseconds 60s default
function onTweet() {
document.getElementById(“tweet”).src = “progress.gif”;
document.getElementById(“label”).innerHTML = “Tweeting…”;
document.getElementById(“message”).disabled = true;
var message = document.getElementById(“message”).value;
var url = “http://”+user+”:”+password+”@twitter.com/statuses/update.xml?status=” + escape(message);
var request = new XMLHttpRequest();
request.onload = function() {
document.getElementById(“tweet”).src = “tweet.jpg”;
document.getElementById(“label”).innerHTML = “Tweet”;
document.getElementById(“message”).disabled = false;
document.getElementById(“message”).value = “”;
}
request.open(“POST”, url);
try{
request.send(null);
}catch( e){
// Will place the Exception in the message Box.
document.getElementById(“message”).value=e;
}
request.onreadystatechange = function(){
if(request.readyState == 4){
//If you want to do specific things when it’s Tweeted Successfully.
}
}
}
function onCheckTimeline() {
var url = “http://”+user+”:”+password+”@twitter.com/statuses/friends_timeline.json”;
var request = new XMLHttpRequest();
request.onload = function() {
var messages = JSON.parse(request.responseText);
document.getElementById(“text”).innerHTML = “”;
for (var i = 0; i < itemsToDisplay; i++)
document.getElementById(“text”).innerHTML +=
‘<img style=”padding-left: 5px; padding-right: 5px;” width=”20″ height=”20″ src=”‘ +
messages[i][“user”][“profile_image_url”] +'” /><div>’ +
messages[i][“user”][“name”] + “: ” + messages[i][“text”] + ” <b>|</b> &nbsp;  </div>”;
}
request.open(“GET”, url);
request.send(null);
}
</script>
<head><script>
setTimeout ( “onCheckTimeline()”, timeToRefresh );
</script>
</head>
<img src=”twitter.png” height=”24″>
<input id=”message” type=”text” />
<div class=”toolstrip-button” onclick=”onTweet()”>
<img id=”tweet” src=”tweet.jpg”>
<span id=”label”>Tweet</span>
</div>
<div class=”toolstrip-button” onclick=”onCheckTimeline()”>
<img src=”refresh.jpg”>
</div>
<marquee style=”border-left: 1px solid lightblue;” truespeed=”truespeed” scrolldelay=”20″ scrollamount=”1″ id=”text” width=”100%”></marquee>

As you can see, the user interface aspect of Chrome extensions consists purely of conventional HTML. You don’t need to learn any API at least for the basic UI. Though to extend it, chrome provides a few custom CSS classes that can be used to apply styling that is consistent with the look and feel of the rest of the browser, another similarity to Palm’s Pre WebOS. And that is why the last few lines all you see is virgin HTML.

Note that in the above snippet, the extension uses the “toolstrip-button” class to make the “Tweet” div element look like a regular Chrome button. If you remove this class-reference, it will look like a standard web form button.

Chrome 4 Extensions

The Execution: When the user clicks the Tweet button, it calls the getElementById DOM method to access the input textbox message. Then it applies escape function so that the text can safely be transmitted as a URL parameter. then, we append it to a URL string that points to Twitter’s status update REST method. Finally, the message is sent using an HTTP POST operation.

Since this is a lame example, Username and password has to be set in the HTML file manually.

If you want to enhance this to have it configured and stored based on user’s input, you can create a preferences page and store the user/password info with the HTML5 localStorage feature, which Chrome and (even Firefox beta builds) supports.

While the request is being sent, it replaces the button icon with an animation LOADING and disables the input textbox and button.

The second thing this extension does is, gets your Friend’s Timelines every 60 seconds. This information is shown via standard HTML Marquee tag. I’ve customized the scrolling speed via special attributes, that make it look pretty, easier to read. Again, XMLHttpRequest is used to communicate with Twitter’s rest API. Next, a simple HTML string with the message contents and the user’s Twitter profile icon is generated and injected into the marquee element.

If you look carefully, there is a <head> that refreshes this by calling the onCheckTimeline every 60s. Time interval can be changed at the top from timeToRefresh. Also, itemsToDisplay can be configured to set max items per fetch.

Now all is set for You to import the extension into Chrome.

Basically, Chrome 4 supports to formats:

1. Compressed .crx files

2. Uncompressed Folder Imports

The first one is nothing but a zipped version of 2nd. You can either download .crx file into chrome to use it or import a folder.

Chrome 4 Extensions

Installing Extension into Chrome 4.0

Download this zipped file and uncompress into a directory. Open twitter.html in an editor and change user / password to that of your Twitter account.

Browse to “chrome://extensions” in chrome to open the panel that let’s you Load Unpacked Extension and browse, select the  folder.

You are done.

Note: I`ll be Enhancing this Extension to parse URLs, @twitter ids, Reply to individuals, many more. Subscribe to RSS or Check back again soon.

Feel Free to modify the code and redistribute it. Don’t forget to give credits to Author.

You can refer to the Twitter API and do wonders with it. It needs some parsing mechanism, but it’s not hard.

So Era of Chrome OS starts, where you write apps that run inside your Browser 😉

GD Star Rating
loading...
GD Star Rating
loading...

14 thoughts on “How To Write Google Chrome Extensions”

  1. Chrome 4 is awesome, and their WebOS idea too!

    Thanks for sharing this wonderful post Taran Fx, u have made lives of many people easy 🙂

    GD Star Rating
    loading...
    GD Star Rating
    loading...
    Reply
  2. Hi, I just thought you should know I’ve been using TwitterFX as the name of my Twitter client in JavaFX for the better part of a year now.

    You might have a clash if you try and register the name with Twitter as an API client.

    GD Star Rating
    loading...
    GD Star Rating
    loading...
    Reply
  3. Do you think you could change the name of the sample client from twitterFX? A quick google search reveals there is already a twitter client of that name in use (and it is built on JavaFX, hence the FX addition being more valid for it).

    GD Star Rating
    loading...
    GD Star Rating
    loading...
    Reply
  4. I can't understand.. How did you added twitter bar in the bottom of chrome window???
    I tried to do it in Chrome v5.x but can't…(((

    GD Star Rating
    loading...
    GD Star Rating
    loading...
    Reply
  5. Hello I am so glad I found your blog page, I really found you by error,
    while I was browsing on Digg for something else, Anyways I am here now and would
    just like to say thanks for a marvelous post and a all round
    interesting blog (I also love the theme/design), I don’t
    have time to read through it all at the moment but I have bookmarked it and
    also added in your RSS feeds, so when I have time I will be back to read more, Please do keep up the fantastic
    job.

    GD Star Rating
    loading...
    GD Star Rating
    loading...
    Reply

Leave a Comment

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