How to set an iframe src attribute from a variable in AngularJS
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()}}">
Related videos on Youtube
![emersonthis](https://i.stack.imgur.com/JU2sZ.png?s=256&g=1)
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, 2020Comments
-
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 returnsTrustedValueHolderType
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 attributesrc="{{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 over 10 yearsThe documentation provides this advice in case one is binding to more than one expression in
ng-src
orsrc
. Angular 1.2 onwards, one can bind to only one expression insrc
andng-src
and the advice is to retrieve an url from the code using a function, if needed. -
Sajith over 10 yearsBut I think there is some mistake in your code. The controller should be like this app.controller('AppCtrl', function($scope) {});
-
musically_ut over 10 yearsControllers can be Globally accessible functions as well.
-
Sajith over 10 yearsOk. Check this link I checked your code with plunker. plnkr.co/edit/caqS1jE9fpmMn5NofUve
-
Sajith over 10 yearsI have noticed a function "trustSrc" in your code. Please remove that function and try again like this . {{trustSrc(currentProject.url)}} to {{currentProject.url}}
-
emersonthis over 10 yearsI 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 over 10 yearsTry using
trustAsResourceUrl
. -
musically_ut over 10 yearsThe plunker uses Angular 1.0.8?
-
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 over 10 yearstrustAsResourceUrl seems to return the same object as trustAsUrl()
-
emersonthis over 10 years...but this one works when I pass it into the ng-src attribute! Thanks.
-
musically_ut over 10 years@Emerson
trustAsResourceUrl
returns a$sce.RESOURCE_URL
which is needed foriframe
/objects
whiletrustAsUrl
returns a$sce.URL
which is a weaker sort of guarantee (and is currently unused as per the documentation). -
baacke over 9 yearsng-src didn't work for me unless I removed the double curly braces( ng-src="currentProjectUrl" )
-
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 needng-src
at all, just thesrc
attribute will suffice. -
RevanProdigalKnight over 9 yearsAnnoyingly, you have to include
$sce
in the controller code, and can't include it in services. -
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!!