How to let script to use setAttribute 'style' without braking CSP

Im am trying to keep my CSP policy as strict as possible. I need to include 3d party component in my bundle. But it uses element.setAttribute('style'...) method which breaks CSP. Is there a way to allow this particular script to inline styles in that manner?

1 answer

  • answered 2017-06-17 20:05 sideshowbarker

    The only way to allow style attributes is to use unsafe-inline. It doesn’t matter whether the style attributes are coming from a different origin or from self—they’re still going to be considered a CSP violation unless you have unsafe-inline.

    Specifically, one solution that won’t work for style attributes is to use a nonce or hash—because in CSP, nonce and hash usage are only defined for style and script elements; the spec has a Hash usage for style elements section that explicitly omits defining hash use for style attributes.

    So even if in your policy you specify the correct hash for the contents of a style attribute, your browser will still handle it as a violation.

    The bottom line is that since unsafe-inline is the only way to allow style attributes—but using unsafe-inline pretty much completely defeats the purpose of having any CSP policy to begin with—the only safe solution from a CSP perspective is just to never use style attributes—neither directly from your own markup/code nor by way of any third-party code.