Chrome Extension - Content Security Policy - executing inline code

Amit G picture Amit G · Sep 2, 2014 · Viewed 44.4k times · Source

I am using an external JavaScript lib in my chrome extension. I has inline execution, so I get following kind of error

(The error I get on console)

Refused to execute JavaScript URL because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension://". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

The error message clearly says there is a work-around possible.

Chrome-Content Security Policy says not possible. Many related question cited this link.

Blog This blogger says it is possible, but probably this is applicable to only older chrome extension.

Any work around possible?

PS: don't wanna/can't change the entire library I am using.

EDIT: how to use hash or nonce to enable inline execution.

Answer

Xan picture Xan · Sep 2, 2014

No, this is not possible to relax this policy. unsafe-inline is specifically ignored by Chrome Extensions since manifest version 2.

Documentation (emphasis mine):

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.

The error message mentions several possible ways, but the docs are clear that no CSP will allow inline scripting, and ignoring unsafe-inline is but one of the measures.

Update

As of Chrome 46, inline scripts can be whitelisted by specifying the base64-encoded hash of the source code in the policy. This hash must be prefixed by the used hash algorithm (sha256, sha384 or sha512). See Hash usage for elements for an example.

See this answer for more in-depth look at whitelisting.