I am writing a chrome extension. And I want to use jQuery
in my extension. I am not using any background page, just a background script.
Here are my files :
manifest.json
{
"manifest_version": 2,
"name": "Extension name",
"description": "This extension does something,",
"version": "0.1",
"permissions": [
"activeTab"
],
"browser_action": {
"default_icon": "images/icon_128.png"
},
"background": {
"scripts": ["background.js"],
"persistent": false
},
"icons": {
"16": "images/icon_16.png",
"48": "images/icon_48.png",
"128": "images/icon_128.png"
}
}
My background.js
file just runs another file named work.js
// Respond to the click on extension Icon
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.executeScript({
file: 'work.js'
});
});
The main logic of my extension is inside work.js
. The contents of which I don't think matters here for this question.
What I want to ask is how can I use jQuery in my extension. Since I am not using any background page. I can't just add jQuery to it. So how can I add and use jQuery into my extension ?
I tried running jQuery along with my work.js from background.js
file.
// Respond to the click on extension Icon
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.executeScript({
file: 'thirdParty/jquery-2.0.3.js'
});
chrome.tabs.executeScript({
file: 'work.js'
});
});
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).
And I would also like to know what's the correct and best way to use third party libraries, in my 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 :If you need jquery in a content_scripts, you have to add it in the manifest too:
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
.Apart from the solutions already mentioned, you can also download
jquery.min.js
locally and then use it -For downloading -
manifest.json -
in html -
Reference - https://developer.chrome.com/extensions/contentSecurityPolicy
Its very easy just do the following:
add the following line in your mainfest.json
now you are free to load jquery directly from url
Source :google doc
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:
Or, generalized:
Or, promisified (and brought more in line with the proper signature):
Or, why the heck not,
async
/await
-ed for even clearer syntax:Note, in Firefox you can just use
browser.tabs.executeScript
as it will return a Promise.