Reputation: 483
my Chrome extension has two files: content and background scripts. I need to add jQuery to content script from cdn and lodash to background script from cdn too.
In my manifest I tried to add lodash from cdn like this:
"background": {
"scripts": ["background.js", "https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"]
},
"content_security_policy": "script-src 'self' https://cdn.jsdelivr.net; object-src 'self'"
But that didn't help.
My content file is injected to the page from the background file:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
chrome.tabs.insertCSS(null, {file: "mainStyles.css"});
chrome.tabs.executeScript(null, {
code: 'var config = ' + JSON.stringify(config)
}, function() {
chrome.tabs.executeScript(null, { file: "https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js" }, function() {
chrome.tabs.executeScript(null, { file: "content.js" })
});
});
}
});
And as you can see I tried to include jQuery from cdn but this way it's not included either.
Maybe someone knows the way how to do this? Many thanks in advance!
Upvotes: 26
Views: 27633
Reputation: 760
You can get your scripts from external resources, but it's not the preferred way as stated here.
Furthermore, you shouldn't use the background
tag like this. Source
You're better off downloading and bundling your extension with required libraries and getting it as a content_script.
Example from my manifest.json
for an extension running on youtube:
"content_scripts": [ {
"matches": ["http://*.youtube.com/*", "https://*.youtube.com/*"],
"js": ["jquery.js", "content.js"]
}],
If you must use some external scripts, I found that doing it using a little hack works the best.
The general idea is that it executes a piece of JS code in the scope of current webpage and adds a <script>
tag with your desired script.
This is a snippet from an extension that required some of our proprietary js to be included:
chrome.tabs.executeScript(tab.id, {code:
"document.body.appendChild(document.createElement('script')).src = 'https://example.com/script.js';"
});
And chrome being such a good guy just executes it.
Upvotes: 29