Content-Security-Policy
HTTP response header or meta tag.css()
functionjQuery code that calls the css()
function to set the style
attribute of an element may be blocked by CSP. You should change such code to use addClass
if possible.
attr()
functionjQuery code that calls the attr()
function to set the style
attribute, or any javascript event handler attribute (eg onclick, onmouseover, etc) of an element will be blocked by CSP.
For jQuery code that attempts to set a javascript event handler attribute, you should change such code to use jQuery's event handlers instead if possible. For example:
$(selector).attr('onclick', 'doSomething()');
$(selector).click(doSomething);
Using the jQuery click
or on()
event handlers hook directly into the browser events without needing to inject HTML attributes into the DOM. CSP is cool with that.
In Firefox you might get an error when loading a jQuery 1.x version with a Content-Security-Policy header, such as:
Content Security Policy: The page's settings blocked the loading of a resource at inline ("script-src"). jquery-1.12.4.js:4743
If you look at that bit of code in jQuery, you will see this:
// Support: IE<9 (lack submit/change bubble), Firefox (lack focus(in | out) events) ... // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) div.setAttribute( eventName, "t" );
So as you can see the jQuery authors are well aware of CSP, but are doing this to patch browser features that might be lacking.
Are you aware of other issues with implementing CSP with jQuery? Let me know, so we can update this page.
Want to learn the ins and outs CSP? Grab a copy of the CSP Developer Field Guide. It's a short and sweet guide to help developers get up to speed quickly.
Grab a CopyAdvisory Week is a weekly roundup of all the security advisories published by the major software vendors.