My First Chrome Extension

In order to learn how to write chrome extensions I wanted to write an extension that would display the title from the current page in a popup like this:

Screenshot of Chrome Extension

The first thing to work out about Chrome extensions is the context within which they run. There are two cases. First there is the code running in the context of Chrome extensions. In this context you can access information about browser things, e.g. names of tabs, access bookmarks etc. And this is the context in which to make UI interactions such as showing popups. Second there is the DOM of the loaded page. The access of extensions to the DOM is tightly separated from the wider Chrome extension context.

I need to access the page's DOM in order to read the title element. To do this I use the chrome.tabs.executeScript method which lets you inject some javascript code into a page, let it run in the context of the page's DOM, and register a callback to receive the results. The code I inject is then just a very simple access of the title element document.getElementsByTagName('title')[0].text;. The only other wrinkle to take care of is that this code must not run until the DOMContentLoaded event has been fired indicating that the browser has built the DOM tree.

Here's the full list of files needed ot make this work...

  1. manifest.json -- the Chrome extension manifest file describing how the extension works
  2. popup.html -- a very simple page that the Chrome extension uses to display the title
  3. popup.js -- the javascript file that makes the call to grab the title element