How to use jQuery in chrome extension? How to use jQuery in chrome extension? google-chrome google-chrome

How to use jQuery in chrome extension?


You have to add your jquery script to your chrome-extension project and to the background section of your manifest.json like this :

  "background":    {        "scripts": ["thirdParty/jquery-2.0.3.js", "background.js"]    }

If you need jquery in a content_scripts, you have to add it in the manifest too:

"content_scripts":     [        {            "matches":["http://website*"],            "js":["thirdParty/jquery.1.10.2.min.js", "script.js"],            "css": ["css/style.css"],            "run_at": "document_end"        }    ]

This is what I did.

Also, if I recall correctly, the background scripts are executed in a background window that you can open via chrome://extensions.


Its very easy just do the following:

add the following line in your manifest.json

"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'",

Now you are free to load jQuery directly from url

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

Source: google doc


And it works fine, but I am having the concern whether the scripts added to be executed in this manner are being executed asynchronously. If yes then it can happen that work.js runs even before jQuery (or other libraries which I may add in future).

That shouldn't really be a concern: you queue up scripts to be executed in a certain JS context, and that context can't have a race condition as it's single-threaded.

However, the proper way to eliminate this concern is to chain the calls:

chrome.browserAction.onClicked.addListener(function (tab) {    chrome.tabs.executeScript({        file: 'thirdParty/jquery-2.0.3.js'    }, function() {        // Guaranteed to execute only after the previous script returns        chrome.tabs.executeScript({            file: 'work.js'        });    });});

Or, generalized:

function injectScripts(scripts, callback) {  if(scripts.length) {    var script = scripts.shift();    chrome.tabs.executeScript({file: script}, function() {      if(chrome.runtime.lastError && typeof callback === "function") {        callback(false); // Injection failed      }      injectScripts(scripts, callback);    });  } else {    if(typeof callback === "function") {      callback(true);    }  }}injectScripts(["thirdParty/jquery-2.0.3.js", "work.js"], doSomethingElse);

Or, promisified (and brought more in line with the proper signature):

function injectScript(tabId, injectDetails) {  return new Promise((resolve, reject) => {    chrome.tabs.executeScript(tabId, injectDetails, (data) => {      if (chrome.runtime.lastError) {        reject(chrome.runtime.lastError.message);      } else {        resolve(data);      }    });  });}injectScript(null, {file: "thirdParty/jquery-2.0.3.js"}).then(  () => injectScript(null, {file: "work.js"})).then(  () => doSomethingElse).catch(  (error) => console.error(error));

Or, why the heck not, async/await-ed for even clearer syntax:

function injectScript(tabId, injectDetails) {  return new Promise((resolve, reject) => {    chrome.tabs.executeScript(tabId, injectDetails, (data) => {      if (chrome.runtime.lastError) {        reject(chrome.runtime.lastError.message);      } else {        resolve(data);      }    });  });}try {  await injectScript(null, {file: "thirdParty/jquery-2.0.3.js"});  await injectScript(null, {file: "work.js"});  doSomethingElse();} catch (err) {  console.error(err);}

Note, in Firefox you can just use browser.tabs.executeScript as it will return a Promise.