Using jQuery in a Chrome extension

I’ve gotten so used to using jQuery that when suddenly I’m reduced to using vanilla javascript I feel like something is wrong. So when I was trying to write a chrome extension and realized I was going to have to use the basic methods to create elements and traverse the DOM, I felt a little squicked out.

There are basically two places you might want to use jQuery in an extension: within the background page, and within a tab. But in both cases, you’re probably going to want to have a local copy of jQuery, which you can get from jquery.com. You could pull it from a CDN but then you’re depending on your internet connectivity and the CDN.

In a background page

This is the simpler of the two. Just include the javascript file in your background.html (or whatever you’ve named it) file in the same way as you would normally.

<script src='jquery-1.5.1.min.js'></script>

In a tab

If you want to use it in a script that runs on each page, you have to modify your manifest.json file to add it to the content_scripts list:

{
  "name": "My Extension",
  "version": "0.1",
  "content_scripts": [
    {
      "matches": ["http://*/*"],
      "js": ["jquery-1.5.1.min.js", "myScript.js"]
    }
  ],
  "background_page": "background.html"
}

Make sure that you put the jquery file first in the list so it is available to your other javascript files, otherwise you will get errors like “$ does not exist”, which plagued me until I realized this.

Notes:

Chrome Extension Dev Guide