简体   繁体   English

如何从AngularJS中的变量设置iframe src属性

[英]How to set an iframe src attribute from a variable in AngularJS

I'm trying to set the src attribute of an iframe from a variable and I can't get it to work... 我正在尝试从变量设置iframe的src属性,我无法让它工作......

The markup: 标记:

<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>

controllers/app.js: 控制器/ app.js:

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 );

    }
}

With this code, nothing gets inserted into the iframe's src attribute. 使用此代码,不会将任何内容插入到iframe的src属性中。 It's just blank. 它只是空白。

Update 1: I injected the $sce dependancy into the AppCtrl and $sce.trustUrl() now works without throwing errors. 更新1:我将$sce依赖注入AppCtrl,$ sce.trustUrl()现在可以正常工作而不会抛出错误。 However it returns TrustedValueHolderType which I'm not sure how to use to insert an actual URL. 但是它返回TrustedValueHolderType ,我不确定如何使用它来插入实际的URL。 The same type is returned whether I use $sce.trustUrl() inside the interpolation braces in the attribute src="{{trustUrl(currentProjectUrl))}}" or if I do it inside the controller when setting the value of currentProjectUrl. 无论我在属性src="{{trustUrl(currentProjectUrl))}}"的插值括号内使用$ sce.trustUrl(),还是在设置currentProjectUrl的值时在控制器内执行,都会返回相同的类型。 I even tried it with both. 我甚至试过两个。

Update 2: I figured out how to return the url from the trustedUrlHolder using .toString() but when I do that, it throws the security warning when I try to pass it into the src attribute. 更新2:我想出了如何使用.toString()从trustedUrlHolder返回url,但是当我这样做时,它会在我尝试将其传递给src属性时抛出安全警告。

Update 3: It works if I use trustAsResourceUrl() in the controller and pass that to a variable used inside the ng-src attribute: 更新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 );

}

My problem seems to be solved by this, although I'm not quite sure why. 我的问题似乎已经解决了,虽然我不太清楚为什么。

I suspect looking at the excerpt that the function trustSrc from trustSrc(currentProject.url) is not defined in the controller. 我怀疑看到来自trustSrc(currentProject.url)的函数trustSrc未在控制器中定义的摘录。

You need to inject the $sce service in the controller and trustAsResourceUrl the url there. 你需要在控制器中注入$sce服务 ,并在那里注入trustAsResourceUrl url

In the controller: 在控制器中:

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

In the Template: 在模板中:

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

It is the $sce service that blocks URLs with external domains, it is a service that provides Strict Contextual Escaping services to AngularJS, to prevent security vulnerabilities such as XSS, clickjacking, etc. it's enabled by default in Angular 1.2. 它是$sce服务,用于阻止带有外部域的URL,它是一种为AngularJS提供严格上下文转义服务的服务,用于防止安全漏洞,如XSS,点击劫持等,它在Angular 1.2中默认启用。

You can disable it completely, but it's not recommended 您可以完全禁用它,但不建议这样做

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

for more info https://docs.angularjs.org/api/ng/service/$sce 更多信息https://docs.angularjs.org/api/ng/service/$sce

this way i follow and its work for me fine, may it will works for you, 这种方式我跟着它,对我的工作很好,可能它会对你有用,

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

here trustThisUrl is just filter, 在这里trustThisUrl只是过滤器,

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

Please remove call to trustSrc function and try again like this . 请删除对trustSrc函数的调用, trustSrc再次尝试。 {{trustSrc(currentProject.url)}} to {{currentProject.url}}. {{trustSrc(currentProject.url)}}到{{currentProject.url}}。 Check this link http://plnkr.co/edit/caqS1jE9fpmMn5NofUve?p=preview 查看此链接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. 但是根据Angular Js 1.2文档,你应该编写一个获取src url的函数。 Have a look on the following code. 看看下面的代码。

Before: 之前:

Javascript 使用Javascript

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

Html HTML

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;
};

But for security reason they are recommending following method 但出于安全考虑,他们建议采用以下方法

Javascript 使用Javascript

 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 HTML

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

select template; 选择模板; iframe controller, ng model update iframe控制器,ng模型更新

index.html 的index.html

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.html Iframe.html的

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

Check this link: http://plnkr.co/edit/TGRj2o?p=preview 请检查此链接: http//plnkr.co/edit/TGRj2o?p = preview

You need also $sce.trustAsResourceUrl or it won't open the website inside the iframe: 您还需要$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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM