我正在尝试使用ng-bind-html和 $ sce.trustAsHtml 阻止执行不安全的内容。
但是,如果我在 标记内放置一些 js (例如 onerror =“ alert(123)” ),它将执行不安全的操作内容。
var app = angular.module('app', []);
app.controller('test', function($scope, $sce, $timeout) {
$scope.text = $sce.trustAsHtml('<ul><b>onLoad<img src=x onload="alert(\'onload\')"/></b></ul>'+'<ul><b>onError<img src=x onerror="alert(\'onerror\')"/></b><ul>'+'<ul><b>onClick<img src=x onclick="alert(\'onclick\')"/></b></ul>');
});
<script src="https://code.angularjs.org/1.7.4/angular.min.js"></script>
<div ng-app="app" ng-controller="test">
Run time binding of HTML
<div ng-bind-html="text"></div>
</div>
能否请您提出一些建议,以防止在此执行js代码?
编辑
根据@Quentin建议[和ng-bind-html doesn't prevent cross site scripting,我删除了trustAsHtml调用并允许进行清理,但ng-bind-html指令仍在$ watch中调用trustAsHtml并出现错误。
var app = angular.module('app', []);
app.controller('test', function($scope) {
$scope.text = '<ul><b>onLoad<img src=x onload="alert(\'onload\')"/></b></ul>'+'<ul><b>onError<img src=x onerror="alert(\'onerror\')"/></b><ul>'+'<ul><b>onClick<img src=x onclick="alert(\'onclick\')"/></b></ul>';
});
<script src="https://code.angularjs.org/1.7.4/angular.min.js"></script>
<div ng-app="app" ng-controller="test">
Run time binding of HTML
<div ng-bind-html="text"></div>
</div>
var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
return {
restrict: 'A',
compile: function ngBindHtmlCompile(tElement, tAttrs) {
var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function sceValueOf(val) {
// Unwrap the value to compare the actual inner safe value, not the wrapper object.
return $sce.valueOf(val);
});
$compile.$$addBindingClass(tElement);
return function ngBindHtmlLink(scope, element, attr) {
$compile.$$addBindingInfo(element, attr.ngBindHtml);
scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
// The watched value is the unwrapped value. To avoid re-escaping, use the direct getter.
var value = ngBindHtmlGetter(scope);
element.html($sce.getTrustedHtml(value) || '');
});
};
}
};
}];
引发以下错误
Error: [$sce:unsafe] Attempting to use an unsafe value in a safe context.
https://errors.angularjs.org/1.7.3/$sce/unsafe
at angular.js:138
at htmlSanitizer (angular.js:20119)
at getTrusted (angular.js:20320)
at Object.sce.(:8080/lia/anonymous function) [as getTrustedHtml] (http://localhost:9000/js/angularjs/lib/angular/angular.js:21040:16)
at ngBindHtmlWatchAction (angular.js:27610)
at Scope.$digest (angular.js:19102)
at Scope.$apply (angular.js:19462)
at bootstrapApply (angular.js:1944)
at Object.invoke (angular.js:5121)
at doBootstrap (angular.js:1942)
我正在使用角度v1.7.4。 你能帮我吗?
答案 0 :(得分:1)