I've been seeing this error while I try to load my chrome extension:
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' https://ajax.googleapis.com".
Here is part of my manifest.json:
...
"background": {
"scripts": ["launcher.js"]
},
"options_page": "options.html",
"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'",
"permissions": [
"tabs", "notifications", "http://*/*", "https://*/*"
...
In whole of my javascript I've only been communicating with https://ajax.googleapis.com and I've ensured with the Network tab of Inspect views.
And I've verified all my javascript code sits inside my .js file only. (And yes I'm using addEventListener() wherever necessary.
Any suggestions?
UPDATE: Showing code responsible for the error (asked by Rob)
This is the only place where I'm communicating with ANY server:
....
$.ajax({
type: "get",
url: "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=" + storyCount + "&callback=?",
data: {
q: link,
output: "json_xml"
},
async: false,
dataType: "json",
success: function (data) {
if (data.responseStatus == 200) {
//process JSON
}
....
With the Change from Manifest Version 1 to 2 . Chrome Extension do not allow you to use inline javascript. You need to place all your javascript inside a .JS file and include it inside the html page.
Also remove all onclick, onchange,onsubmit to eventlistner events.
Thanks
This error message has nothing to do with the requests you do to other servers - it is about inline scripts. If you don't have any inline scripts then most likely it comes up because somewhere you are creating code dynamically, by means of eval(), new Function() or similar. For example, jQuery will do that to parse JSON if it doesn't find JSON.parse() method (in Chrome this method should normally be available however). From the info you gave here it is impossible to tell which code is responsible for the error.
Regardless of that, you should definitely not use JSONP as Rob W correctly noted in the comments. JSONP will execute code from a remote server in the context of your extension which is inherently insecure - theoretically it would only call the callback but practically it could also do something malicious. You should use JSON instead (data being downloaded and parsed, no remote code execution) and remove ajax.googleapis.com from your Content Security Policy.
Related
I am working on a project in Django, where I am using a javascript from an external payment provider. Upon calling their script, they will insert a payment form embedded in my page.
The documentation on how to integrate with their service is found here. Specifically I am following step 3 and 4.
A snippet of my html is as below. Upon calling my javascript the payment form from checkout.js will be rendered as an iframe in the checkout-container-div element
<div id="checkout-container-div"> </div>
<script src="https://test.checkout.dibspayment.eu/v1/checkout.js?v=1"></script>
In my javascript, I first call my backend to get the paymentId. Then using the obtained paymentId, I am calling the external checkout.js with const checkout = new Dibs.Checkout(checkoutOptions); in order to render the payment form
document.getElementById("paymentButton").addEventListener("click", function() {
//Collect all the fields value and send it to the server
console.log("pay button clicked")
$.ajax({
url : "localDeliveryPayment",
type : "get",
success: function(response) {
if (response['paymentIdCreation'] == true) {
console.log(response);
const checkoutOptions = {
checkoutKey: response['checkoutKey'], // Replace!
paymentId: response['paymentId'],
containerId: "checkout-container-div",
};
const checkout = new Dibs.Checkout(checkoutOptions);
checkout.on('payment-completed', function (response) {
window.location = 'completed.html';
});
}
}
})
})
From Google Chrome's console I get the following error related to test.checkout.dibspayment.eu/:1
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'sha256-NzNw/hrx7wC5UKemwLm4mwVnoDVfHDuSpmZAeKCQaqY=' 'sha256-aKaLBqGLMQ35mP/i/QmpW+s6QnrN3dNb78G9ndv1bC0=' 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='". Either the 'unsafe-inline' keyword, a hash ('sha256-1XgMsIi6szxMi7JX5ZCg4KWReddGOu15C+cKuzlVaf4='), or a nonce ('nonce-...') is required to enable inline execution.
Also I see this error related to checkout.api.ts:126 POST
POST https://test.checkout.dibspayment.eu/api/v1/frontendlogs net::ERR_ABORTED 401 (Unauthorized)
There are some other errors as well that I think is related to content being blocked. I have tried to add the below meta tag to the head in my html base template.
<meta http-equiv="Content-Security-Policy"
content = "script-src 'self'
cdnjs.cloudflare.com
code.jquery.com
cdn.jsdelivr.net
stackpath.bootstrapcdn.com
test.checkout.dibspayment.eu;">
Still I got the error test.checkout.dibspayment.eu/:1
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'sha256-NzNw/hrx7wC5UKemwLm4mwVnoDVfHDuSpmZAeKCQaqY=' 'sha256-aKaLBqGLMQ35mP/i/QmpW+s6QnrN3dNb78G9ndv1bC0=' 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='". Either the 'unsafe-inline' keyword, a hash ('sha256-1XgMsIi6szxMi7JX5ZCg4KWReddGOu15C+cKuzlVaf4='), or a nonce ('nonce-...') is required to enable inline execution.
Also I tried with 'unsafe-inline' keyword in the Content-Security-Policy meta tag, but still got the same error. I have read several places that CSP is blocking for inline code execution and now is really confused if the issue at all is related to inline code execution from the external javascript, or if this error is related to something else?
The solution to this problem on integration of NETS payment service when running in Django turned out not to be fully related to content security protocol. The error I posed originally is related to CSP, but I never managed to solve it. When I used the payment demo webshop I see the same error on my browser as during my own test. The checkout was successful, therefore I figured out that the error is not only related to CSP. It turned out that adding
django_referrer_policy.middleware.ReferrerPolicyMiddleware'
to the middleware in my settings.py and followed by adding
REFERRER_POLICY = 'strict-origin'
in settings.py solved the problem.
I'm trying to retrieve informations from PHP script on localhost
app.js on Cordova application :
var url = 'http://localhost:8000/locations';
$.ajax({
url: url,
type: 'GET',
contentType: "application/json",
async: true,
dataType: 'jsonp',
crossDomain: true,
success: function(resp){
console.log(resp);
},
error: function(err) {}
});
and the php code (with Laravel framwork)
return Location::all()->toJson();
I have this error
Refused to load the script
'http://localhost:8000/locations?callback=jQuery21309354114597663283_1431278135791&_=1431278135792'
because it violates the following Content Security Policy directive:
"default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'".
Note that 'script-src' was not explicitly set, so 'default-src' is
used as a fallback.
You need to add policies to your Cordova app.
http://content-security-policy.com/
http://www.html5rocks.com/en/tutorials/security/content-security-policy/
Second link is exactly what you need, article is well written I can quote only:
https://apis.google.com/js/plusone.js in the context of this page’s
origin. We trust that code, but we can’t expect the browser to figure
out on it’s own that code from apis.google.com is awesome, while code
from apis.evil.example.com probably isn’t. The browser happily
downloads and executes any code a page requests, regardless of source.
Instead of blindly trusting everything that a server delivers, CSP
defines the Content-Security-Policy HTTP header that allows you to
create a whitelist of sources of trusted content, and instructs the
browser to only execute or render resources from those sources. Even
if an attacker can find a hole through which to inject script, the
script won’t match the whitelist, and therefore won’t be executed.
I just added this in the head tag
<access origin="*" />
and it works !
I am developing a test page, which will used only by myself and only with Google Chrome. Is there any way to perform cross domain requests to 3rd party server (which doesn't allow such requests) with such conditions? The requests could be GET or OPTIONS.
(I am aware about Chrome extensions like Advanced REST client, which could perform such requests, but it doesn't help me since complex calculations should be performed prior to request execution)
One option is to disable the same-origin policy entirely, as detailed in Disable same origin policy in Chrome. This will probably do the trick for you, but it's a bit inelegant, as it turns off the same-origin policy for the entire browser instance.
A second option is to create a small Chrome extension that holds all of the files that you need to load. It will make your files accessible via chrome-extension://... and only files within that extension will be immune from the same-origin policy.
Create a new folder, put your testing Web page in it, and create a manifest.json file in the same folder:
/testing_extension
test_page_immune_from_same_origin.html
script_used_by_test_page.js
styles_for_test_page.css
manifest.json
The contents of manifest.json should be
{
"name": "All-origin access extension",
"manifest_version": 2,
"version": "1.0",
"permissions": ["<all_urls>"]
}
Load the extension by going to chrome://extensions, enabling Developer Mode, and selecting the new folder with Load unpacked extension... option.
You can view your page as an extension resource chrome-extension://[app_id]/[file_name], where "app_id" is the hash listed for the extension on the chrome://extensions page. (It will be a long string of lowercase letters.) Now when the page performs cross-origin resources, it does so with the authority of a browser extension, unrestricted by the same-origin policy.
Note that you will need to move any inline scripts into separate files in order to comply with extension CSP requirements.
One way is to serve your files off a webserver rather than the local file system. Another way is to start Chrome with a flag:
chrome --disable-web-security
(From Cross-origin image load denied on a local image with THREE.js on Chrome)
A more extensive list of flags is here: http://peter.sh/experiments/chromium-command-line-switches/
I'm working on a project similar to this and I had to upload a simple html file to one of my prod servers for testing so I could test the cross domain functionality.
The html file pointed to localhost, so it would only work for me while in development.
The jquery code looked like this (just in case it helps):
$.ajax({
type: "POST",
dataType: "json",
cache: false,
url: url,
data: data,
crossDomain: true,
success: function (data) {
ATSJBAjax = null;
if (callback != null) callback(data);
}
});
Also I'm using c#/MVC, and I had to add an attribute to all controller methods that added "Access-Control-Allow-Origin" to the response header so Chrome would be OK with it. I called the attribute "AllowCrossDomainAccess", which ref'd the class below:
public class AllowCrossDomainAccessAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
base.OnActionExecuting(filterContext);
}
}
I'm trying to send a request from chrome packaged app:
$.ajax({
url: "https://accounts.google.com/o/oauth2/auth?client_id=xxxapps.googleusercontent.com&response_type=id_token&scope=openid%20email", //"https://www.googleapis.com/plus/v1/people/me",
jsonp: "responseText",
dataType: "jsonp",
data: {
q: "select *",
format: "json"
},
success: function( response ) {
console.log( response );
}
});
and recieving the following error:
Refused to load the script
'https://accounts.google.com/o/oauth2/auth?client_id=xxx&q=select+*&format=json&_=xxx'
because it violates the following Content Security Policy directive:
"default-src 'self' chrome-extension-resource:". Note that
'script-src' was not explicitly set, so 'default-src' is used as a fallback.
The manifest file of the app contains following:
"content_security_policy": "script-src 'self' https://accounts.google.com; object-src 'self'"
How to fix this error?
The error messages you're seeing are the answer. The first one was saying you were violating CSP. The second is saying you can't change CSP in a Chrome App.
Read more about Content Security Policy in a Chrome App, and for completeness another discussion in the context of Chrome Extensions. You have the answer to the question you asked, but you might want to ask a new question explaining what you're trying to do (as opposed to why you're seeing these error messages). If your overall goal is to run external (i.e., downloaded) content in a Chrome App, the only way to do it according to the Chrome Web Store's developer terms of service is to sandbox the code and message to/from your normal, privileged code.
I think I've solved it by adding to manifest:
"permissions": ["https://accounts.google.com/"]
I'm working on an extension for Chrome that uses an RSS parser, however I have used several different methods and I keep getting the error: "XMLHttpRequest cannot load Example.rss. Origin chrome extension://djhppbppokfmldecpcfbcmchagimpmpc is not allowed by Access-Control-Allow-Origin."
Tried using the AJAX feed and jFeed methods in the first answer below but neither worked for me.
How to parse an RSS feed using JavaScript?
Here's my JavaScript function:
jQuery.getFeed({
url: 'http://example.rss',
success: function(feed) {
alert(feed.title);
}});
My Manifest.JSON looks like
"manifest_version": 2,
"version": "1.0",
"permissions": ["http://*/", "tabs"],
Any help would be greatly appreciated.
You need to add CSP in your manifest.
Something like this line, but change example.com to your feed:
content_security_policy": "script-src 'self' https://example.com; object-src 'self'
For more read this: CSP in Chrome extensions
Your specified host permission is missing a path.
Change http://*/ to http://*/*
For more info, see the chrome documentation on match patterns.