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:
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
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
only other wrinkle to take care of is that this code must not run
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...
- manifest.json -- the Chrome extension manifest file describing how the extension works
- popup.html -- a very simple page that the Chrome extension uses to display the title