How to use jquery in google chrome extension page action background.js?

User picture User · Oct 25, 2012 · Viewed 32.2k times · Source

I'm developing a "page action" google chrome extension. My manifest has:

...
"background": { "scripts": ["background.js"] },
...

In my background.js file I have:

function doSomething() {
     alert("I was clicked!");
}

chrome.pageAction.onClicked.addListener(doSomething);

This works. Now in my doSomething function I want to read some data on the current page. It will be a lot easier for me to use jquery to read the data so I can easily target the exact data I want. How can I incorporate jquery (preferrably served from google's CDN) so that it's accessible to my doSomething function?

Answer

Jaydeep Solanki picture Jaydeep Solanki · Jan 2, 2013

The "background" specification in manifest.json should specify jquery.js so that it is loaded before background.js:

...
"background": { "scripts": ["jquery.js","background.js"] },
...

This should do the job.
Remember the js files are loaded in the order they are specified.

test if jquery is loaded.

in background.js

if (jQuery) {  
    // jQuery loaded
} else {
    // jQuery not loaded
}