出于明显的原因(防止攻击),我使用以下两个过滤器的组合首先从用户输入中删除所有 HTML,然后替换
标记中的所有\n。
<span data-ng-bind-html-unsafe="model.userInput | noHTML | newlines"></span>
filters.filter('newlines', function () {
return function(text) {
console.log(text)
return text.replace(/\n/g, '<br/>');
}
})
filters.filter('noHTML', function () {
return function(text) {
return Boolean(text) ? text
.replace(/&/g, '&')
.replace(/>/g, '>')
.replace(/</g, '<') : '';
}
});
问题是在 angular 1.2.2 中 bind-html-unsafe 被弃用,你必须使用 $sce(严格的上下文转义)来“信任 html”,它返回一个函数,我显然不能在其上应用那些过滤器。
新代码:
ctrls.controllers('someCtrl', function($scope, $sce){
$scope.trusterInput = $sce.trustAsHtml($scope.userInput);
});
错误:
TypeError: Object [object Object] has no method 'replace'
at Scope.<anonymous> (http://localhost:8000/js/filters.js:20:20)
at fnInvoke (http://code.angularjs.org/1.2.2/angular.js:9756:21)
at OPERATORS.| (http://code.angularjs.org/1.2.2/angular.js:9271:59)
at extend.constant (http://code.angularjs.org/1.2.2/angular.js:9701:14)
at OPERATORS.| (http://code.angularjs.org/1.2.2/angular.js:9271:74)
at extend.constant (http://code.angularjs.org/1.2.2/angular.js:9701:14)
at Object.getStringValue (http://code.angularjs.org/1.2.2/angular.js:16990:41)
at Scope.$digest (http://code.angularjs.org/1.2.2/angular.js:11494:47)
at Scope.$apply (http://code.angularjs.org/1.2.2/angular.js:11740:24)
at http://code.angularjs.org/1.2.2/angular.js:13265:36
显然是因为 $sce 返回一个函数而不是原始类型('text' 的值):
TrustedValueHolderType {$$unwrapTrustedValue: function, $$unwrapTrustedValue: function, valueOf: function, toString: function, valueOf: function…}
$$unwrapTrustedValue: function () {
arguments: (...)
get arguments: function ThrowTypeError() { [native code] }
set arguments: function ThrowTypeError() { [native code] }
caller: (...)
get caller: function ThrowTypeError() { [native code] }
set caller: function ThrowTypeError() { [native code] }
length: 0
name: ""
prototype: Object
__proto__: function Empty() {}
<function scope>
__proto__: TrustedValueHolderType
关于如何解决这个问题的任何想法,除了在 $sce 之前以编程方式调用我的过滤器之外,这几乎不是 Angular 做事的方式
最佳答案
与其编写您自己的 HTML 转义器,不如让自动转义器为您完成,而不是用 <br>
替换换行符只需使用 CSS 属性 white-space: pre
.
TypeError: Object [object Object] has no method 'replace'
at Scope.<anonymous> (http://localhost:8000/js/filters.js:20:20)
发生是因为text
不是字符串——上下文自动转义器已经为您完成了第一步,并将字符串转换为特权 SCE 安全 HTML 值。
$sce.trustAsHtml($scope.userInput)
有风险。如果他们正在 socially engineered,将天真的用户的输入作为 HTML 回传给他们可能是危险的复制/粘贴真正来自攻击者的文本。
关于javascript - 将\n 替换为我在 $sce.trustAsHtml() 上使用的模型变量上的 <br> 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20330294/