Saturday, October 8, 2011

Chrome Browser Extension

I recently wrote about building a Firefox extension for our website, Narf.com. The process involved many XML files including learning XUL to display the simple menu in our extension. Chrome on the other hand, is an extremely lightweight extension which begins with the following manifest file:


The permissions and browser_action items are the only ones worth describing. Google describes permissions better than I can but the basic idea is that you need to tell Chrome what your extension is allowed to do. I specify that I need acccess to 'tabs' because I use the chrome.tabs and chrome.windows module. I also request access to narf.com.

Browser Actions are used to add an icon to the Google toolbar after the address field. This adds an icon in the same way as the Chrome wrench icon.

The browser action defines popup.html which is the page that is displayed when the icon is clicked. This page is simply a HTML page that you can use all your knowledge of HTML on. I found this approach much easier to wrap my head around than Firefox's reliance on XUL. Here is a portion of our popup.html:


As you can see the html itself is some extremely simply divs which call out onClick handlers which I define in the script above. I removed the more complex examples that are specific to our site, but left two simple ones that demonstrate how the Javascript is used to interact with the Chrome browser.

The first, refreshNarfTabs, is used to refresh all tabs which are currently displaying a narf.com address. This is achieved by first getting the current window, which is the browser window where the action was invoked. This then calls an anonymous function where we get all the tabs in the current window. Then for each tab we check to see if 'narf' is in the url and refresh it. You'll notice a lot of the Chrome APIs rely on callbacks because much of it is asynchronous.

The other function I include for reference is showNarf which opens a new tab with the Narf.com homepage. It is pretty simple which is exactly how it's supposed to be. The window.close() at the top is just to close the popup window that displays the menu.

The nice thing about Chrome extensions is that it's just HTML. You don't have to learn a new GUI system or language to build something pretty powerful.

No comments:

Post a Comment