Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 526
User Avatar asked Oct 25 '12 08:10

User


People also ask

Can we use jQuery in Chrome extension?

You can just put jquery. js into extension folder and include it in the manifest: { "name": "My extension", ... "content_scripts": [ { "matches": ["http://www.google.com/*"], "css": ["mystyles.

What are background scripts?

Background scripts are the place to put code that needs to maintain long-term state, or perform long-term operations, independently of the lifetime of any particular web pages or browser windows.

What is background js?

The background script ('background. js') is a JavaScript script that runs once our extension either gets installed or the user refreshes the extension manually.


1 Answers

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 } 
like image 122
Jaydeep Solanki Avatar answered Oct 05 '22 23:10

Jaydeep Solanki