我的ng-bind-html
指令存在问题。
我从外部服务(不受信任)获取电子邮件HTML数据,因此我可能会在邮件正文中收到<script>
标记。但是我不想在我的页面上执行这个JS代码。我正在使用ng-bind-html
指令。
我为此创建了一个示例,我的问题是执行了alert()
函数。如何否认这样做?
var app = angular.module('myApp', ['ngSanitize']);
app.controller('MainCtrl', function ($sce, $scope) {
$scope.text = " <script>alert(222)</script> <script>alert(222)</script>";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MainCtrl">
<div ng-bind-html="text"></div>
</div>
答案 0 :(得分:1)
由于您引用了旧版本的AngularJS,因此无法获得正确的错误,因此很难解释。我以类似的方式尝试并发现错误,这表明包含<script>
的绑定文本存在一些问题。
实际上,当一个终止
script
标记时,就像 - &gt;</script>
,编译器生成错误,显示为无效。
在我为一个项目工作时发生了这种情况,开发人员故意删除</script>
以防止任何运行时错误。否则整个代码就会中断。
我不知道它背后的实际原因,但它过去曾为我们做过伎俩。
因此,在我的代码demo中,脚本不会自行运行;因此,对于您的情况,只是删除或阻止script
标记的结束/关闭,可能就是这样做。
同时,您可以使用以下代码:
<强> HTML:强>
<div ng-app="app" ng-controller="test">
Run time binding of HTML
<div ng-bind-html="text"></div>
</div>
<强> JS:强>
var app = angular.module('app', []);
app.controller('test', function($scope, $sce, $timeout) {
$scope.bindHTML = "<script>alert(123);";
$scope.text = $sce.trustAsHtml($scope.bindHTML);
});
答案 1 :(得分:1)
使用DOMPurify在呈现数据之前清理数据。它是最好的HTML清洁剂。另一个选择是逃避整个事情,但我想可能还有其他HTML标签需要保留吗?
答案 2 :(得分:0)
您正在将$sce
服务注入您的控制器,所以看起来您已经到了一半了。您可以在文本上运行$sce.trustAsHtml(text)
功能,并相应地对其进行清理。
有关详细信息,请参阅文档:https://docs.angularjs.org/api/ng/service/ $ sce
修改:或者,考虑使用$sanitize
服务与$sce
,https://docs.angularjs.org/api/ngSanitize/service/ $ sanitize
$sanitize(text);
答案 3 :(得分:0)
我看不到任何:
<script src="angular-sanitize.js">
在您的代码中,因为AngitJS Core中不包含sanitize。
这是一个解释实现它的正确方法的链接: http://blog.timsommer.be/using-ngsanitize-to-render-html-strings-in-angular/