Cross Post From StackOverflow.
I am attempting to use the new Content Security Policy (CSP) HTTP headers on a test site. When I use CSP in conjunction with Modernizr I get CSP violation errors. This is the CSP policy I am using:
Content-Security-Policy: default-src 'self'; script-src 'self' ajax.googleapis.com ajax.aspnetcdn.com; style-src 'self'; img-src 'self'; font-src 'self'; report-uri /WebResource.axd?cspReport=true
These are the errors from the Chrome browser console:
Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self'".
Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.
window.Modernizr.injectElementWithStyles - modernizr-2.7.2.js:134
window.Modernizr.tests.touch - modernizr-2.7.2.js:457(anonymous function)
modernizr-2.7.2.js:949(anonymous function) - modernizr-2.7.2.js:1406
I discovered the following workaround on the Github Modernizr site. However, the wrokaround was first put forward in March and doing a little Google-Fu I can find no fixes or workarounds to this issue.
I know that I can include the unsafe-inline directive which can get around this error but this also enables unsafe code to run and negates the use of CSP in the first place. Does anyone have any solutions.
Hey @RehanSaeed!
The only fix would be to rewrite the portion of Modernizr causing the error. If you have any other comments or questions, could you add it to the existing issue, rather than a new one? just so that we can keep everything in one place.
Thanks!
I'm also stuck with this problem. Is there a way that perhaps the modernizr development team knows of, to deploy or fetch a version of a modernizr js file that does not violate CSP?
hey @blachawk!
Nothing has changed since the last update. You would want to ensure your build is only what you need to actually detect, and then create a nonce for the file and add that as a whitelisted source for style-src (or whatever rule is being triggered)
Might be necessary to this info to the docs?
given there are two comments in two years on the top issue for "modernizr csp", and knowing the worldwide CSP usage rates (which is...not high) I think putting this in the docs would cause more confusion than actual help. A blog post explaining how to go about using nonces would proably be best
I see. Speaking of blog posts, there is still one missing fro 3.6.0 https://github.com/Modernizr/modernizr-neue/pull/124
I'd also prepare a 3.7 one during the weekend.