Skip to content

Instantly share code, notes, and snippets.

@oslego
Last active December 19, 2015 10:49
Show Gist options
  • Save oslego/5943581 to your computer and use it in GitHub Desktop.
Save oslego/5943581 to your computer and use it in GitHub Desktop.
How to build a Google Chrome DevTools extension where content scripts can access the node selected in the 'Elements' panel.

[Writting in progress] Chrome Developer Tools extensions and The Selected Element

This article is about building extensions for Google Chrome Developer Tools, also known as Chrome DevTools. Specifically, you'll learn how to work with element that is currently selected in the 'Elements' panel. Prior knowledge about DevTools extensions is required. Check out Boris Smus's Extending Chrome Developer Tools for an introduction and read through Google's own documentation on Chrome Extensions.

Chrome Extensions and Chrome DevTools Extensions

You can build extensions for the Google Chrome browser itself, which are targeted at regular users, as well as extensions for Chrome DevTools - the set of panels that developers use to inspect and audit content on web pages.

A Chrome DevTools extension has additional fields in its manifest.json file:

Isolated worlds

Chrome extensions are draconically sandboxed pieces of code with intricate and limited scope of exectution. Of course, this is good for the user's security and privacy. The extensions architecture was built with all the good intentions, but this doens't make development it any sweeter.

In the manifesto file, you'll have to declare all files and services that the extension is allowed to acces. Different pages of the same extension can't talk directly to each another. Message passing must be employed and it's mostly based on serialzed JSON with a weight limit.

Content script isolated world DevTools extension wold

Getting the selected element

The devtools extension HTML page and the JavaScript files linked to it are the only ones that have access to the chrome.devtools API.

As a developer, you can get access to the selected element from the 'Elements' panel by invoking a JavaScript expression in the context of the web page that's being inspected. This uses the chrome.devtools.inspectedWindow API.

// TODO: fix code to be relevant chrome.devtools.inspectedWindow.eval( "jQuery.fn.jquery", function(result, isException) { if (isException) console.log("the page is not using jQuery"); else console.log("The page is using jQuery v" + result); } );

Working with the selected element

Chrome DevTools evolved from the WebKit Web Inspector. As such, it is intended to inspect web pages and their content.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment