Programing

Angular 1.2 이상에서 ng-bind-html-unsafe를 복제하기 위해 $ sce.trustAsHtml (string)을 어떻게 사용합니까?

lottogame 2020. 4. 20. 19:14
반응형

Angular 1.2 이상에서 ng-bind-html-unsafe를 복제하기 위해 $ sce.trustAsHtml (string)을 어떻게 사용합니까?


ng-bind-html-unsafe Angular 1.2에서 제거되었습니다

사용할 필요가있는 것을 구현하려고합니다 ng-bind-html-unsafe. 문서와 github commit에서 그들은 말합니다 :

ng-bind-html은 $ sce.trustAsHtml (string)의 결과에 바인딩 될 때 ng-html-bind-unsafe와 같은 동작 (내 HTML이 살균되지 않은 결과)을 제공합니다.

어떻게합니까?


다음과 같아야합니다.

<div ng-bind-html="trustedHtml"></div>

컨트롤러에 플러스 :

$scope.html = '<ul><li>render me please</li></ul>';
$scope.trustedHtml = $sce.trustAsHtml($scope.html);

$scope.html변수를 직접 참조 할 수있는 오래된 구문 대신 :

<div ng-bind-html-unsafe="html"></div>

여러 의견자가 지적했듯이 $sce컨트롤러에 주입해야 $sce undefined합니다. 그렇지 않으면 오류가 발생합니다.

 var myApp = angular.module('myApp',[]);

 myApp.controller('MyController', ['$sce', function($sce) {
    // ... [your code]
 }]);

필터

app.filter('unsafe', function($sce) { return $sce.trustAsHtml; });

용법

<ANY ng-bind-html="value | unsafe"></ANY>

개인적으로 데이터베이스에 들어가기 전에 일부 PHP 라이브러리로 모든 데이터를 삭제하므로 다른 XSS 필터가 필요하지 않습니다.

AngularJS 1.0.8에서

directives.directive('ngBindHtmlUnsafe', [function() {
    return function(scope, element, attr) {
        element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
        scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) {
            element.html(value || '');
        });
    }
}]);

쓰다:

<div ng-bind-html-unsafe="group.description"></div>

비활성화하려면 $sce:

app.config(['$sceProvider', function($sceProvider) {
    $sceProvider.enabled(false);
}]);

var line = "<label onclick="alert(1)">aaa</label>";

1. 필터 사용

app.filter('unsafe', function($sce) { return $sce.trustAsHtml; });

(html) 사용 :

<span ng-bind-html="line | unsafe"></span>
==>click `aaa` show alert box

2. ngSanitize 사용 :보다 안전

포함 angular-sanitize.js

<script src="bower_components/angular-sanitize/angular-sanitize.js"></script>

ngSanitize루트 각도 앱에 추가

var app = angular.module("app", ["ngSanitize"]);

(html) 사용 :

<span ng-bind-html="line"></span>
==>click `aaa` nothing happen

간단히 필터를 생성하면 트릭을 수행 할 수 있습니다. (앵귤러 1.6에 대한 답변)

.filter('trustHtml', [
        '$sce',
        function($sce) {
            return function(value) {
                return $sce.trustAs('html', value);
            }
        }
    ]);

그리고 html에서 다음과 같이 사용하십시오.

<h2 ng-bind-html="someScopeValue | trustHtml"></h2>

이전 지시문을 다시 원한다면 이것을 앱에 추가 할 수 있습니다.

지령:

directives.directive('ngBindHtmlUnsafe', ['$sce', function($sce){
    return {
        scope: {
            ngBindHtmlUnsafe: '=',
        },
        template: "<div ng-bind-html='trustedHtml'></div>",
        link: function($scope, iElm, iAttrs, controller) {
            $scope.updateView = function() {
                $scope.trustedHtml = $sce.trustAsHtml($scope.ngBindHtmlUnsafe);
            }

            $scope.$watch('ngBindHtmlUnsafe', function(newVal, oldVal) {
                $scope.updateView(newVal);
            });
        }
    };
}]);

용법

<div ng-bind-html-unsafe="group.description"></div>

출처-https://github.com/angular-ui/bootstrap/issues/813


자바 스크립트

$scope.get_pre = function(x) {
    return $sce.trustAsHtml(x);
};

HTML

<pre ng-bind-html="get_pre(html)"></pre>

들어 레일 당신이 사용하는 경우 (내 경우에는 적어도) 보석 - 레일 AngularJS와을 의 살균 모듈을 추가하는 것을 기억하십시오

//= require angular
//= require angular-sanitize

그런 다음 앱에로드하십시오 ...

var myDummyApp = angular.module('myDummyApp', ['ngSanitize']);

그런 다음 다음을 수행 할 수 있습니다.

템플릿에서 :

%span{"ng-bind-html"=>"phone_with_break(x)"}

그리고 결국 :

$scope.phone_with_break = function (x) {
  if (x.phone != "") {
   return x.phone + "<br>";
  }
  return '';
}

my helpful code for others(just one aspx to do text area post)::

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication45.WebForm1" %>

<!DOCTYPE html>

    enter code here

<html ng-app="htmldoc" xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="angular.min.js"></script>
    <script src="angular-sanitize.min.js"></script>
    <script>
        angular.module('htmldoc', ['ngSanitize']).controller('x', function ($scope, $sce) {
            //$scope.htmlContent = '<script> (function () { location = \"http://moneycontrol.com\"; } )()<\/script> In last valid content';
            $scope.htmlContent = '';
            $scope.withoutSanitize = function () {
                return $sce.getTrustedHtml($scope.htmlContent);
            };
            $scope.postMessage = function () {
                var ValidContent = $sce.trustAsHtml($scope.htmlContent);

                //your ajax call here
            };
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        Example to show posting valid content to server with two way binding
        <div ng-controller="x">
            <p ng-bind-html="htmlContent"></p>
            <textarea ng-model="htmlContent" ng-trim="false"></textarea>
            <button ng-click="postMessage()">Send</button>
        </div>
    </form>
</body>
</html>

참고 URL : https://stackoverflow.com/questions/18340872/how-do-you-use-sce-trustashtmlstring-to-replicate-ng-bind-html-unsafe-in-angu

반응형