source

Angular 변수에서 iframe src 속성을 설정하는 방법JS

itover 2022. 11. 2. 21:35
반응형

Angular 변수에서 iframe src 속성을 설정하는 방법JS

src이프람

마크업:

<div class="col-xs-12" ng-controller="AppCtrl">

    <ul class="">
        <li ng-repeat="project in projects">
            <a ng-click="setProject(project.id)" href="">{{project.url}}</a>
        </li>
    </ul>

    <iframe  ng-src="{{trustSrc(currentProject.url)}}">
        Something wrong...
    </iframe>
</div>

컨트롤러/app.disples:

function AppCtrl ($scope) {

    $scope.projects = {

        1 : {
            "id" : 1,
            "name" : "Mela Sarkar",
            "url" : "http://blabla.com",
            "description" : "A professional portfolio site for McGill University professor Mela Sarkar."
        },

        2 : {
            "id" : 2,
            "name" : "Good Watching",
            "url" : "http://goodwatching.com",
            "description" : "Weekend experiment to help my mom decide what to watch."    
        }
    };

    $scope.setProject = function (id) {
        $scope.currentProject = $scope.projects[id];
        console.log( $scope.currentProject );

    }
}

iframe에는 .src 이에요. 그냥빈칸칸이에요냥냥공공공공공공

업데이트 1: I intracted the permission for the p$sceAppCtrl s $sce.trustUrl() 입니다.단, 반환됩니다.TrustedValueHolderTypeURL을 잘 . $sce.()에서 내에 $trustUrl됩니다.src="{{trustUrl(currentProjectUrl))}}"current ProjectUrl은 현재 ProjectUrl이다.둘 다 써보기도 했어요.

업데이트 2: .toString()을 사용하여 trustedUrlHolder에서 URL을 반환하는 방법을 알아냈습니다만, 이 경우 src 속성에 URL을 전달하려고 하면 보안 경고가 발생합니다.

업데이트 3: 컨트롤러에서 trustAsResourceUrl()을 사용하여 ng-src 속성 내에서 사용되는 변수에 전달하면 동작합니다.

$scope.setProject = function (id) {
    $scope.currentProject = $scope.projects[id];
    $scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
    console.log( $scope.currentProject );
    console.log( $scope.currentProjectUrl );

}

왜 그런지 모르겠지만 이것으로 제 문제는 해결된 것 같습니다.

I suspect looking at the excerpt that the function 발췌문을 보면 그 함수가trustSrc부에서trustSrc(currentProject.url)컨트롤러에서 정의되지 않습니다.컨트롤러에 정의되어 있지 않습니다.

컨트롤러에 서비스를 삽입해야 합니다.trustAsResourceUrl그 theurl저기 있네.

컨트롤러 내:

function AppCtrl($scope, $sce) {
    // ...
    $scope.setProject = function (id) {
      $scope.currentProject = $scope.projects[id];
      $scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
    }
}

템플릿:

<iframe ng-src="{{currentProjectUrl}}"> <!--content--> </iframe>

그것은 로 바 it그 is the it?$sce외부 도메인과 같은 보안 취약점을 차단하는 서비스입니다. XSS에 의한 보안 취약점을 제공하는 서비스이다.외부 도메인이 있는 URL을 차단하는 서비스입니다.는 각도JS에 엄격한 컨텍스트 이스케이프 서비스를 제공하여 XSS, 클릭잭킹 등의 보안 취약점을 방지하고 Angular 1.2에서 기본적으로 활성화되어 있습니다.

완전히 비활성화할 수 있지만 권장되지 않습니다.

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

자세한 것은, https://docs.angularjs.org/api/ng/service/$sce 를 참조해 주세요.

이렇게 하면 내가 따라갈 수 있고 나에게도 효과가 있어, 너에게도 효과가 있기를,

<iframe class="img-responsive" src="{{pdfLoc| trustThisUrl }}" ng-style="{
                height: iframeHeight * 0.75 + 'px'
            }" style="width:100%"></iframe>

여기 신뢰이 Url은 필터일 뿐입니다.

angular.module("app").filter('trustThisUrl', ["$sce", function ($sce) {
        return function (val) {
            return $sce.trustAsResourceUrl(val);
        };
    }]);

Please remove call to 콜을 삭제해 주세요.trustSrc다음과 같이 기능하고 다시 시도합니다. {{trustSrc(currentProject.url)}} ~ {{currentProject.url}}.이 링크를 체크합니다.http://plnkr.co/edit/caqS1jE9fpmMn5NofUve?p=preview


But according to the Angular Js 1.2 Documentation, you should write a function for getting src url. Have a look on the following code.

이전:

자바스크립트

scope.baseUrl = 'page';
scope.a = 1;
scope.b = 2;

HTML

<!-- Are a and b properly escaped here? Is baseUrl controlled by user? -->
<iframe src="{{baseUrl}}?a={{a}&b={{b}}"

그러나 보안상의 이유로 다음과 같은 방법을 권장합니다.

자바스크립트

var baseUrl = "page";
scope.getIframeSrc = function() {

  // One should think about their particular case and sanitize accordingly
  var qs = ["a", "b"].map(function(value, name) {
      return encodeURIComponent(name) + "=" +
             encodeURIComponent(value);
    }).join("&");

  // `baseUrl` isn't exposed to a user's control, so we don't have to worry about escaping it.
  return baseUrl + "?" + qs;
};

HTML

<iframe src="{{getIframeSrc()}}">

템플릿 선택; iframe 컨트롤러, ng 모델업데이트

index.displaces를 표시합니다.

angularapp.controller('FieldCtrl', function ($scope, $sce) {
        var iframeclass = '';
        $scope.loadTemplate = function() {
            if ($scope.template.length > 0) {
                // add iframe classs
                iframeclass = $scope.template.split('.')[0];
                iframe.classList.add(iframeclass);
                $scope.activeTemplate = $sce.trustAsResourceUrl($scope.template);
            } else {
                iframe.classList.remove(iframeclass);
            };
        };

    });
    // custom directive
    angularapp.directive('myChange', function() {
        return function(scope, element) {
            element.bind('input', function() {
                // the iframe function
                iframe.contentWindow.update({
                    name: element[0].name,
                    value: element[0].value
                });
            });
        };
    });

iframe.syslog

   window.update = function(data) {
        $scope.$apply(function() {
            $scope[data.name] = (data.value.length > 0) ? data.value: defaults[data.name];
        });
    };

다음 링크를 확인합니다.http://plnkr.co/edit/TGRj2o?p=preview

또,$sce.trustAsResourceUrl그렇지 않으면 iframe 내의 웹사이트가 열리지 않습니다.

angular.module('myApp', [])
    .controller('dummy', ['$scope', '$sce', function ($scope, $sce) {

    $scope.url = $sce.trustAsResourceUrl('https://www.angularjs.org');

    $scope.changeIt = function () {
        $scope.url = $sce.trustAsResourceUrl('https://docs.angularjs.org/tutorial');
    }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="dummy">
    <iframe ng-src="{{url}}" width="300" height="200"></iframe>
    <br>
    <button ng-click="changeIt()">Change it</button>
</div>

언급URL : https://stackoverflow.com/questions/20045150/how-to-set-an-iframe-src-attribute-from-a-variable-in-angularjs

반응형