Writing Chrome Extensions
I love Google. I truly do. Not because of all the “free” stuff they let you use, but because of the endless supply of development tools and resources one can get from them. Be that Web Fonts or Hosted libraries or their SDK’s and API’s.
I recently came across a tutorial on writing your own Chrome extensions, and frankly was surprised how easy it came out be. I recommend reading the tutorial.
For a person with even mediocre understanding of HTML and JavaScript it shouldn’t pose a problem to put together a simple extension of their own.
You start with preparing a manifest.json
file, which pretty much is what its name implies. This describes the extension and by means of the permissions
settings allows for example to bypass Same origin policy, shoud you want to use AJAX, but we will focus on something very simple - namely injecting your code into the document loaded in the currently selected tab.
manifest.json
{ "name": "A browser action running JQuery on loaded docs DOM", "version": "1.0", "background": { "scripts": ["background.js"] }, "permissions": [ "http://*/*" ], "browser_action": { "name": "Run me!" }, "manifest_version": 2 }
Now we have to fashion up a background.js
file with a listener which will be triggered by the event of pressing the extension button. The triggered action will be loading the jquery.min.js
, and as its callback executing the short JQuery code, which adds the word test at the begining of documents body contents.
background.js
chrome.browserAction.onClicked.addListener(function(tab) { chrome.tabs.executeScript(null, {file:"jquery.min.js"}, function() { chrome.tabs.executeScript(null, {code:"$('body').prepend('Test');"}); }); });
After that you just make sure all the files are saved in the same directory and:
- start Chrome
- open the extensions tab (chrome://extensions)
- check the developer mode
- click “load unpacked extension”
- select your extension directory
…and that’s the whole shebang. Your extension should be loaded, which will be indicated by the little puzzle piece icon top right corner. After that load up a page and test it. Each time you press it, the word “Test” wrapped in h1
tags in should be added to the beginning of the documents body.
That’s hardly a useful extension but you can do much more, for example:
- add a nifty download button to a site like YouTube
- change the looks of pages you visit by hiding parts of them, or changing their looks altogether
- communicate with Chromes options and features
There are loads of ready examples on the Google Chrome Extensions pages, along with more detailed guides explaining what, when and why.