Banned inline style CSP and dynamic positioning of HTML elements

后端 未结 2 1759
忘了有多久
忘了有多久 2020-12-09 07:17

A client has changed their CSP to ban inline styles on their server. As far as I can tell, this means that we can no longer use JS to dynamically position/animate/style HTML

2条回答
  •  粉色の甜心
    2020-12-09 07:34

    The proper workaround for this issue is to use the CSS Object Model (CSSOM).

    Given the following ways of setting the style:

    1. ...

      // fails due to CSP
    2. document.getElementById(id).setAttribute('style', 'left: 343px'); // fails due to CSP
    3. document.getElementById(id).style.left = '343px';

    Only the last one will successfully comply with a CSP directive of style-src: self (because it's using the CSSOM).

    That's why using jQuery's .css() function works:

    When using .css() as a setter, jQuery modifies the element's style property. For example, $( "#mydiv" ).css( "color", "green" ) is equivalent to document.getElementById( "mydiv" ).style.color = "green".

提交回复
热议问题