Google Chrome AngularJS 点击指令的内容保护政策

Google Chrome Content Protection Policy for AngularJS click directives

我遇到了一个非常有趣的场景,如果能从中获得一些见解会很棒。最近我遇到了新的 Google Chrome 的 内容安全策略 不允许 内联脚本或事件HTML 本身内的 onclick 或 ontouch 等悬挂器。简而言之,它 强制要求 我们在单独的文件中使用 javascript 编写这些点击处理程序。

所以而不是写这样的东西:

<input id="addRecordBtn" type="button" value="Add record" onclick="addRecord()">
<input id="refreshBtn" type="button" value="Refresh" onclick="refreshList()">

我最终使用 jQuery 的 on 功能添加了 jquery 事件绑定器,如下所示:

$(document).ready(function(evt){
$('#addRecordBtn').on('click', function(){
    alert("Adding Record");
    AddValueToDB();
});

$('#refreshBtn').on('click', function(){
    alert("Refresh Records");
    ListDBValues();
});

});

现在,上面的方法确保 HTML 是干净的并且没有任何 JavaScript 但它也在我的脑海中产生了一个问题,如果我使用 AngularJS 或类似 ng-click 处理程序的东西。如何摆脱它们?

<input id="addRecordBtn" type="button" value="Add record" ng-click="addRecord()">
<input id="refreshBtn" type="button" value="Refresh" ng-click="refreshList()">

如何才能删除 ng-click 或者我对 ng-click 的理解有误。 ng-click 是否遵循 Chrome 的内容安全策略?

我得到的这方面的文档非常有限。很少有见解会很棒。

谢谢, Ankit.

我希望这篇 link 对您有所帮助。 https://docs.angularjs.org/api/ng/directive/ngCsp

AngularJS 和 Content-Security-Policy 记录在 ngCsp 指令下。以下是 unsafe 规则对 Angular 的影响:

  • unsafe-eval: this rule forbids apps to use eval or Function(string) generated functions (among other things). Angular makes use of this in the $parse service to provide a 30% increase in the speed of evaluating Angular expressions.

  • unsafe-inline: this rule forbids apps from inject custom styles into the document. Angular makes use of this to include some CSS rules (e.g. ngCloak and ngHide). To make these directives work when a CSP rule is blocking inline styles, you must link to the angular-csp.css in your HTML manually.

具体来说ngClick使用了AngularJS表达式...

<ANY
  ng-click="expression">
...
</ANY>

...并且 AngularJS expression 不需要 eval 并使用 Content-Security-Policy.[=29= 的 unsafe 规则]

Angular does not use JavaScript's eval() to evaluate expressions. Instead Angular's $parse service processes these expressions.