There are two ways to include an external library to the background script of an extension in Chrome. I say background script, because that script is the most likely candidate for needing an external library.
To clarify, your background script runs in a different scope from any web page that your users are using. So loading an external library inside the background script won't overwrite anything in the web page in use.
Method 1: Use the scripts
key of the background
key in the manifest file
Inside the value for the scripts
key, add an array which contains reference to the library that you require, and the background script. Note that the order inside the array matters. Script listed first will be loaded first.
Example:
// ...
"background": {
"scripts": ["jquery.min.js", "background.js"]
}
Here, your background page will be constructed automatically by Chrome.
Method 2: Use the page
key of the background
key in the manifest file
Sometimes, it's just not efficient to save a 2.5MB library file inside your project directory.
With this method, you will construct your own background page, with script tag that loads the required background script and libraries remotely.
Remove the script
key from the background
key in the manifest.json
file, and replace it with page
. You can either have the script
key, or the page
key, but you can't have both. The value for the page
is a reference to your background html page.
But that's not enough. Chrome's security policy forbids you from downloading resources remotely.
Hence, modify the content_security_policy
key to relax the default security policy and specify the URL where your background page will download the library.
Example:
//...
"background": {
"page": "background.html",
"persistent": true
},
//...
"content_security_policy": "script-src 'self' http://code.jquery.com; object-src 'self'"