我的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>





https://jsfiddle.net/Suvroc/0c0ee472/8/

最佳答案

由于您已经引用了AngularJS的旧版本,因此无法获取正确的错误,因此很难解释。我以类似的方式尝试并发现了错误,这表明包含<script>的已绑定文本存在一些问题。


  实际上,当人们终止script标记(例如-> </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);
});

10-05 20:35
查看更多