我有一个非常有趣的场景,如果能从中获得一些见解会很棒。最近我发现了新的 Google Chrome 浏览器的内容安全政策,它不允许在 HTML 本身中允许内联脚本或事件 hanglers,如 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 事件绑定(bind)器添加到如下所示的内容中:
$(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 的内容安全政策?
我得到的这方面的文档非常有限。很少有见解会很棒。
谢谢, 安 git 。
最佳答案
AngularJS 和 Content-Security-Policy 记录在 ngCsp 下指示。以下是 unsafe
规则如何影响 Angular:
unsafe-eval
: this rule forbids apps to useeval
orFunction(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
andngHide
). To make these directives work when a CSP rule is blocking inline styles, you must link to theangular-csp.css
in your HTML manually.
特别是ngClick使用 AngularJS 表达式...
<ANY
ng-click="expression">
...
</ANY>
...和 AngularJS expression不需要 eval
并使用 Content-Security-Policy 的 unsafe
规则。
Angular does not use JavaScript's
eval()
to evaluate expressions. Instead Angular's$parse
service processes these expressions.
关于javascript - AngularJS 点击指令的 Google Chrome 内容保护政策,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30415863/