Joel Blum
Joel Blum

Reputation: 7878

Chrome Extensions Content-Security-Policy

I have the need in my extension to dynamically load code . I wrote this to load it -

    var se = document.createElement('script');
se.setAttribute('type', 'text/javascript');
se.appendChild(document.createTextNode(code));
document.getElementsByTagName('head').item(0).appendChild(se);

And this is my security policy in manifest.js -

 "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"

This throws a javascript error -

 "Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe eval'"

My question is - Why isn't it relaxed ? I specifically added the line in manifest to allow unsafe evals .

Upvotes: 4

Views: 3873

Answers (2)

ozzimpact
ozzimpact

Reputation: 111

Simply add this to your manifest.json, worked for me.

 "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"

Upvotes: 1

gowansg
gowansg

Reputation: 795

I don't think it's your use of eval that is causing the error. It appears you're violating the policy against executing inline JavaScript, by injecting <script> blocks into the head of your document.

According to the documentation on Content Security Policy:

Inline JavaScript will not be executed. This restriction bans both inline blocks and inline event handlers (e.g. < button onclick='...'>).

Also note:

Inline Script

There is no mechanism for relaxing the restriction against executing inline JavaScript. In particular, setting a script policy that includes 'unsafe-inline' will have no effect.

Instead of placing your code inline you'll have to come up with an approach that utilizes external js files to accomplish whatever it is that you are trying to do.

Upvotes: 2

Related Questions