如何从XSS atack保护Angular JS?

时间:2015-11-05 20:21:41

标签: angularjs xss

我在聊天中使用ng-repeat来发送消息:

ng-bind-html="message.message + getAttachmentTemplate(message.attachment)"

如何从XSS atack中删除JS,HTML和安全的特殊符号? 但我需要在getAttachmentTemplate

中显示HTML

1 个答案:

答案 0 :(得分:0)

您需要加入angular-sanitize.js,然后才能加载ngSanitize模块

angular.module('app', ['ngSanitize']);

然后,您可以使用$sanitize服务来清理HTML代码段,请参阅以下示例:



angular.module('expressionsEscaping', ['ngSanitize'])
  .controller('ExpressionsEscapingCtrl', function($scope, $sanitize) {
    $scope.msg = 'Hello, <b>World</b>!';
    $scope.safeMsg = $sanitize($scope.msg);
  });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>

<head>
  <meta charset="utf-8">
  <script src="http://code.angularjs.org/1.0.2/angular.js"></script>
  <script src="http://code.angularjs.org/1.0.2/angular-sanitize.js"></script>
  <script src="app.js"></script>
</head>

<body ng-app="expressionsEscaping" ng-controller="ExpressionsEscapingCtrl">
  <div class="container">
    <h2>Angular $sanitize demo</h2>

    <p ng-bind="msg"></p>
    <p ng-bind-html-unsafe="msg"></p>
    <p ng-bind-html="msg"></p>
    <p ng-bind-html-unsafe="safeMsg"></p>

    <div>Provided by <a onclick="window.open('stackoverflow.com')">Stack Overflow</a>
    </div>
  </div>
</body>

</html>
&#13;
&#13;
&#13;