![](/img/trans.png)
[英]Angular js ng-bind-html not giving any output on input `{_}`
[英]Angular ng-bind-html - prevent execution of JS code
我對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>
由於您已經引用了AngularJS的舊版本,因此無法獲取正確的錯誤,因此很難解釋。 我以類似的方式嘗試了一下,發現了錯誤,這表明綁定包含<script>
的文本存在一些問題。
實際上,當終止
script
標記(例如-></script>
,編譯器會生成錯誤,顯示為無效。
在我為一個項目工作時,我就發生了這種情況,開發人員在其中故意刪除</script>
以防止任何運行時錯誤。 否則,整個代碼將中斷。
我不知道其背后的真正原因,但過去它為我們成功了。
因此,在我的代碼演示中 ,腳本不會自行運行。 因此,就您的情況而言,僅刪除或阻止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);
});
在渲染數據之前,請使用DOMPurify清理數據。 這是目前最好的HTML消毒劑。 另一種選擇是逃避整個問題,但是我想您可能還要保留其他HTML標簽嗎?
您正在將$sce
服務注入到控制器中,因此看來您已經完成了一半。 您可以在$sce.trustAsHtml(text)
上運行$sce.trustAsHtml(text)
函數,這將對其進行相應的清理。
有關更多信息,請參閱文檔: https : //docs.angularjs.org/api/ng/service/ $ sce
編輯:或者,研究將$sanitize
服務與$sce
一起使用, https: $sce
$ sanitize
$sanitize(text);
我看不到任何東西:
<script src="angular-sanitize.js">
在您的代碼中,因為AngularJS Core中不包含sanitize。
這是一個解釋正確實現方式的鏈接: http : //blog.timsommer.be/using-ngsanitize-to-render-html-strings-in-angular/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.