尝试使用 angular sanitizer 在我的应用程序上实现 angular sanitizer,但它没有按预期工作。
angular.module('sanitizeExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
//$scope.snippet = "<script type='text/javascript'>alert(1)</script>";
$scope.snippet = "alert(1)";
$scope.deliberatelyTrustDangerousSnippet = function() {
return $sce.trustAsHtml($scope.snippet);
};
$scope.escape = function(input) {
return $sce.trustAsHtml(input);
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-sanitize.js"></script>
<div ng-app="sanitizeExample">
<div ng-controller="ExampleController">
Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
<table>
<tr>
<td>Directive</td>
<td>How</td>
<td>Source</td>
<td>Rendered</td>
</tr>
<tr id="bind-html-with-sanitize">
<td>ng-bind-html</td>
<td>Automatically uses $sanitize</td>
<td><pre><div ng-bind-html="snippet"><br/></div></pre></td>
<td><div ng-bind-html="snippet"></div></td>
</tr>
<tr id="bind-html-with-trust">
<td>ng-bind-html</td>
<td>Bypass $sanitize by explicitly trusting the dangerous value</td>
<td>
<pre><div ng-bind-html="deliberatelyTrustDangerousSnippet()">
</div></pre>
</td>
<td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td>
</tr>
<tr id="bind-default">
<td>ng-bind</td>
<td>Automatically escapes</td>
<td><pre><div ng-bind="snippet"><br/></div></pre></td> <td><div ng-bind="snippet">ggg</div></td>
</tr>
</table>
<p>{{ escape("<script type='text/javascript'>alert(1)</script>") }}</p>
</div>
</div>
引发 Uncaught SyntaxError:使用脚本时出现无效或意外的令牌错误
$scope.snippet = "<script type='text/javascript'>alert(1)</script>"
没有脚本也能正常工作
$scope.snippet = "alert(1)"
它在浏览器中发出警报,但期望 p 标签的内部文本。
<p>{{ escape("<script type='text/javascript'>alert(1)</script>") }}</p>
还可以在 html 中获取输出
{{ 逃脱(””) }}
如何通过从 html 模板调用控制器函数来清理具有脚本标记的变量。