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

261,588

Solution 1

I suspect looking at the excerpt that the function trustSrc from trustSrc(currentProject.url) is not defined in the controller.

You need to inject the $sce service in the controller and trustAsResourceUrl the url there.

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>

Solution 2

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.

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

Solution 3

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,

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

Solution 4

Please remove call to trustSrc function and try again like this . {{trustSrc(currentProject.url)}} to {{currentProject.url}}. Check this link 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.

Before:

Javascript

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

But for security reason they are recommending following method

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

<iframe src="{{getIframeSrc()}}">
Share:
261,588

Related videos on Youtube

emersonthis
Author by

emersonthis

I am a designer, developer, and problem solver. I make websites and stuff. I work with brazen startups, modest individuals, earnest small business, and everyone in between. I care as much about how things look as how they work. I enjoy writing and teaching what I know. The best part about my job is constantly learning new things.

Updated on July 15, 2020

Comments

  • emersonthis
    emersonthis almost 4 years

    I'm trying to set the src attribute of an iframe from a variable and I can't get it to work...

    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:

    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. It's just blank.

    Update 1: I injected the $sce dependancy into the AppCtrl and $sce.trustUrl() now works without throwing errors. However it returns TrustedValueHolderType which I'm not sure how to use to insert an actual 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. 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.

    Update 3: It works if I use trustAsResourceUrl() in the controller and pass that to a variable used inside the ng-src attribute:

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

  • musically_ut
    musically_ut over 10 years
    The documentation provides this advice in case one is binding to more than one expression in ng-src or src. Angular 1.2 onwards, one can bind to only one expression in src and ng-src and the advice is to retrieve an url from the code using a function, if needed.
  • Sajith
    Sajith over 10 years
    But I think there is some mistake in your code. The controller should be like this app.controller('AppCtrl', function($scope) {});
  • musically_ut
    musically_ut over 10 years
    Controllers can be Globally accessible functions as well.
  • Sajith
    Sajith over 10 years
    Ok. Check this link I checked your code with plunker. plnkr.co/edit/caqS1jE9fpmMn5NofUve
  • Sajith
    Sajith over 10 years
    I have noticed a function "trustSrc" in your code. Please remove that function and try again like this . {{trustSrc(currentProject.url)}} to {{currentProject.url}}
  • emersonthis
    emersonthis over 10 years
    I tried it with $sce as you recommended. It causes the error message to go away, but the src attribute of the iframe is still empty.
  • musically_ut
    musically_ut over 10 years
    Try using trustAsResourceUrl.
  • musically_ut
    musically_ut over 10 years
    The plunker uses Angular 1.0.8?
  • emersonthis
    emersonthis over 10 years
    @Sajith please see my updates above. I am able to use trustSrc as you have both suggested, but I can't retrieve the URL from the returned object. I tried calling .toString() on it but it went back to throwing the same error from the beginning.
  • emersonthis
    emersonthis over 10 years
    trustAsResourceUrl seems to return the same object as trustAsUrl()
  • emersonthis
    emersonthis over 10 years
    ...but this one works when I pass it into the ng-src attribute! Thanks.
  • musically_ut
    musically_ut over 10 years
    @Emerson trustAsResourceUrl returns a $sce.RESOURCE_URL which is needed for iframe/objects while trustAsUrl returns a $sce.URL which is a weaker sort of guarantee (and is currently unused as per the documentation).
  • baacke
    baacke over 9 years
    ng-src didn't work for me unless I removed the double curly braces( ng-src="currentProjectUrl" )
  • musically_ut
    musically_ut over 9 years
    @baacke I will be surprised if that is the case, the documentation clearly states that for interpolation, one needs to have {{}} in the expression. If you don't need to interpolate anything, then you do not need ng-src at all, just the src attribute will suffice.
  • RevanProdigalKnight
    RevanProdigalKnight over 9 years
    Annoyingly, you have to include $sce in the controller code, and can't include it in services.
  • Rafique Mohammed
    Rafique Mohammed over 8 years
    $sce.trustAsResourceUrl( works! thanx.. i dnt even knw $sce module is exist and its use.. Angular sucks at this... urrgghh!! i wasted my whole day solving it.. finally i found the ryt solution!!