如何通过增加宽度来增加进度条的大小,但没有任何内联样式,这样它就不会打扰 CSP



这看起来相当直接,有几个选项我正在考虑,但W3说使用内联样式。奇怪的是,像W3这样值得信赖的资源会告诉人们去做一些没有标准化的事情,这是一个安全问题。我想知道是否有专业人士能告诉我关于这个问题的官方立场。https://www.w3schools.com/w3css/w3css_progressbar.asp看到他们已经使用内联样式的宽度。这是我目前实现的,但想改变。

war3解释的很简单,很容易实现。只要在javascript循环中增加内联样式的宽度,你就有了一个基本的进度条。但是,问题是内联样式是XSS攻击的热点,所以因为我使用CSP,我已经消除了所有的内联样式和脚本,除了我的进度条。

有趣的是,从安全脚本添加的内联样式是允许的,并且不会扰乱CSP,然而,在我发现的关于这个主题的任何文档中,100次中有99次会清楚地说,内联样式是一种安全风险,当然它也取决于其他因素,但为了符合最佳实践和安全,我选择删除所有东西,甚至是在live dom上完成的。

那么如何在不使用内联样式的情况下增加循环内的宽度呢?

此链接内容安全策略与可变内联样式(CSP vs CSS)表明,在活动Dom上使用内联样式是可以的,正如其他文章所建议的那样。你不能用el。但是你可以使用el.style。它还说,当CSP 3级被更广泛地采用时,这将是没有问题的。我不确定它是否正确,我很确定最新的chrome有CSP3,我正在测试,我使用的风格仍然被接受。我真的没有看到任何明确的答案。@Thomas你从这个链接中得到了什么?这是我在互联网上以不同的方式发现的评论。这仍然是一个内联样式,不管你如何表示它。仅仅因为你现在可以不受惩罚,并不意味着当CSP Level 3被采用时,你就可以了。这是在转移注意力,还是我的理解是正确的,仅仅因为CSP现在没有稻田,未来就会有。或者更确切地说,这只是一个额外的安全风险,对吧?根据我刚刚读到的文章,我一直在离开它和做些什么之间徘徊。哈哈,一定有人知道官方答案吧?

正如评论中所写的那样,没有办法做到这一点。这是不可能的。别再浪费时间了,去做下一项任务吧。

如果你仍然感兴趣,请往下读,下面的解决方案不是一个解决方案,所以你知道。直接看注释

简单地说,我编辑了样式表规则,而不是添加内联样式。

// this gets the style sheets loaded in the dom as an array
var sheets = document.styleSheets;
//this gets the rules in the form of an array from the first sheet
var rules = sheets[0].cssRules || sheets[0].rules;
// this will be used to mark every iteration of the progress loop.
var i = 0;
// this fires up the function below
progressTimer();

function progressTimer(){
// this sets a timout every 10th of a second 
setTimeout(function(){

// this is used to mark a percentage of progress. In this case because the loop runs every 10th of a second, this will represent 1%
var newwidth = ++i;

//this is setting the new width of the progress bar inside the style sheet 

// NOTE!!! this is instead of setting element.style.prop = val (which is still allowed from a trusted source but probably will break in the future maybe depending on who knows what.) and definately don't do this element.setAttribute(style, ".somerule{prop:val;}"); as that flag an error from CSP

rules[1].style.width = newwidth+'%';

//this checks if we have reached 100% yet
if(newwidth < 100){
// if we have then loop again in a 10th of a second
progressTimer();
}else{
// we are at 100%
// reset the progress width marker
i = 0;
// reset the progress width in the style sheet
rules[1].style.width = '0%'
//run it again just for fun
progressTimer();
}

},100);
}
.barouter{ 
border:solid grey thick;
width:100%;
}
.barinner{ 
height:20px;
background:yellow;
width:0px;

-transition: all 0.1s linear;
-moz-transition: all 0.1s linear;
-o-transition: all 0.1s linear;
transition: all 0.1s linear; 
}
<div class="barouter">
<div class="barinner"></div>
</div>