This Chrome extension tutorial will cover building a basic hello world chrome extension where clicking on extension icon will open a popup window containing active page h1 dom element value.
It is recommended that you complete chrome extension hello world extension tutorial before this tutorial.
Here are the steps for this tutorial.
-
Create manifest.json
Create a directory
hello-world-dom
and createmanifest.json
in that dir. Here is very basic manifest.json for hello world dom extension. Note that this extension needsactiveTab
permission.
{ "name": "Hello World", "description": "Hello World Chrome App.", "version": "0.1", "manifest_version": 2, "permissions": [ "activeTab" ], "browser_action": { "default_icon": "hello-16.png", "default_popup": "popup.html" } }
-
Create default popup html and icon
We’ll use the following popup.html file.
<!DOCTYPE html> <html style="min-width:300px;min-height:300px;"> <head> </head> <body> <div id="id1">-</div> <script type="text/javascript" src="popup.js"></script> </body> </html>
and following popup.js file
var tab_title = ''; function display_h1 (results){ h1=results; document.querySelector("#id1").innerHTML = "<p>tab title: " + tab_title + "</p><p>dom h1: " + h1 + "</p>"; } chrome.tabs.query({active: true}, function(tabs) { var tab = tabs[0]; tab_title = tab.title; chrome.tabs.executeScript(tab.id, { code: 'document.querySelector("h1").textContent' }, display_h1); });
The icon file including full source code is also hosted on github at the link hello-world. Place these three files in hello-world directory. -
Load the hello world dom extension in Chrome
Open chrome extension page by visiting chrome://extensions and then click on load unpacked extension and select hello-world-dom directory.
Once extension is loaded, you will see hello world extension entry in chrome toolbar.
-
Run the extension
Look for the hello world extension icon in Chrome toolbar and click on it. You should be able to see a window popup containing current tab page h1 dom element value.
-
Source code
You can get the source code used in this tutorial from github hello-world-dom.