2016-07-27 61 views
0

如何在angularjs中呈現html之前防止腳本標記注入/加載?

var testApp = angular.module('testApp',['ngSanitize']); 
 
testApp.controller('TestController',function($scope,$sce){ 
 
\t $scope.htmlString = "<span>Test HTML</span><script>alert('Hello Script');</script>"; 
 
\t $scope.toTrusted = function(htmlContent) { 
 
\t \t if(htmlContent && htmlContent != "") { 
 
\t \t \t return $sce.trustAsHtml(htmlContent); \t \t \t 
 
\t \t } 
 
\t \t return ""; 
 
\t }; 
 
});
<html ng-app="testApp"> 
 
<body ng-controller="TestController"> 
 
\t <div ng-bind-html="toTrusted(htmlString)"></div> 
 
\t <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
 
\t <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular-sanitize.min.js"></script> 
 
\t <script type="text/javascript" src="resources/js/controllers/testController.js"></script> 
 
</body> 
 
</html>

我使用NG綁定,HTML渲染字符串作爲html.Sometimes我收到腳本標籤在HTML字符串,我不希望注入/負載腳本tag.So又該我會阻止腳本標記。

我也搜索了這個問題的解決,有人說,剛剛從字符串渲染html.So請有人建議me.What是更好的方式來做到這一點之前刪除腳本標籤?

我正在開發聊天應用程序的幫助下,angularjs和firebase.And用於呈現聊天消息我使用ng-bind-html指令。我注意到,如果用戶發送腳本標記作爲聊天消息的一部分,但給出的腳本是正在運行。所以我想限制這個腳本運行。

+0

好吧,我很困惑。腳本標籤位於您的字符串中。爲什麼你不能把它拿出來? –

+0

您應該清理html字符串以僅允許限制標籤子集。 –

+0

我會清理所有的HTML元素,並實現某種形式的降價語法爲您的聊天消息。使它更安全,同時我發現markdown比HTML更容易編寫此類內容(Think GitHub自述文件)。 – ste2425

回答

0

如果您正在使用$ sce.trustAsHtml,你需要單獨使用NG-綁定。

<div ng-bind="toTrusted(htmlString)"></div> 

試試這個,讓我知道。

+0

但阿迪亞我們不能用NG綁定指令,因爲NG-綁定指令用於替換指定的HTML文本內容 –

相關問題