Pages

Insert HTML, CSS, and JS into any Web Page with a Chrome Extension

Overview

Chrome extensions have pretty good documentation and pretty good community support. Naturally, you might expect that between docs and forums that you can get a small project up and running quickly.

Unfortunately, sometimes minor simple tasks can get lost in the weeds. Documentation usually only covers the basic, small, happy flow cases and forums usually only ask about difficult, large problems. Well what about issues of medium size and complexity? Leave that to the bloggers!

Here we’ll take a look at how to create a chrome extension that uses a Content Script to change the background color of any page using jQuery.

Manifest.json

First things first. You need a way to tell chrome what your intentions are, what components come with your extension, and when they apply. To do this, we’ll use a manifest file.

The manifest file contains some JSON formatted data that Google knows how to read. There is a lot of boiler plate info that you can explore, but, for our purposes, we want to pay special attention to the content script section:

In this case, we’ve specified that we want to our content to run whenever the web url matches the pattern *://*/*, which is to say for all protocols, for all domains, for all pages (in other words, run everywhere).

If you just wanted to target google.com or any of it’s content pages, then you could put that there.

The second thing we’ve specified is which files to run and in which order. First we’ll load jQuery from a local copy that we deploy, and next we’ll run a file called script.js that we’ll look at in a second.

Script.js

In this simplified example, let’s say we just want to change the background color of the current page for a very obvious example of whether or not all the right components have been called. In a real world example, you might want to find all the links in the page and turn them a particular color. Or attach some code to any images on the page to allow you to easily email them. Whatever you want!

For now, let’s just run the following script which will find the body element and use the css() method in jQuery to apply the value blue to the background property:

$(function() {
$("body").css("background","blue");
});

Note: Just so I don’t get comments about it. If this was the only change you wanted to make to the page, you can and should do this purely with CSS. The idea was to add jQuery to a page in a trivial example so you can implement your own functionality later.

Here’s a couple of extensions I’ve built for chrome, along with their source code if you’re looking for examples. Feel free to leave comments on GitHub with any suggestions or bugs using GitHub’s issue tracker.

Link Finder - Find all links to named anchors within the page so you can create descriptive links to content within a page