I’m trying to migrate my Chrome extension to manifest 2. The current version uses a background.html page that is basically one big script tag. Since that is no longer possible, I switched to using a background.js script and after much search and experiments, still failing to inject a script from an external file. In the current version I just use document.write to inject a script tag that will run when the browser loads and I haven’t found a way to do this now.
I’m aware of the chrome.tabs.onUpdated.addListener function and the ability to inject script per tab update using a XMLHttpRequest object, but the script I want to run should do so only when the browser loads.
current code (in a script tag in a background.html file):
document.write("<script type='text/javascript' src='" + url + "'></script>");
In the background.js file this now leads to an error:
Refused to load the script ‘http://www.mydomain.com/script.js’ because it violates the following Content Security Policy directive: “script-src ‘self’ chrome-extension-resource:”.
I’ve tried all sorts of code, including:
var s = document.createElement('script');
s.src = chrome.extension.getURL(url);
s.onload = function() {
this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);
But seems like this will work only for local script files whereas I need to load an external online file.
The error you are getting is due the directive content_security_policy in the manifest. You need to specify the domain of your script as part of it. Here’s an example for jQuery:
And in the Background.html page
This didn’t cause me any error. About to when download this script, that’s up to your extension architecture, but there’s many ways you can tell your application how to do it. Remember that the first thing your application loads is your Background page, so you can do send a message from your Background page to your content script when it’s loaded. Example:
This is an example of when to show a Page action after the tabs was updated. In a previous code:
You can read more about Content Security Policy for Chrome Extensions here and more about Message Passing here.