Banned inline style CSP and dynamic positioning of HTML elements

随声附和 提交于 2019-11-27 02:31:38

问题


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 elements e.g. we can't detect the position of a DOM element and position another element next to it via JS.

Is this correct? Is there a workaround for us to dynamically animate DOM elements with this CSP restriction in place?


回答1:


JavaScript is executed on the client. Unless the filtering software is incredibly clever, you can still add dynamic inline styles as the server has no idea what's happening in the browser. What you can't do, however, is add inline styles as part of the HTML you send to the client.




回答2:


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

Given the following ways of setting the style:

  1. <p style="left: 343px">...</p> // 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".



来源:https://stackoverflow.com/questions/24713440/banned-inline-style-csp-and-dynamic-positioning-of-html-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!