Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$sce.trustAsResourceUrl() globally

Tags:

angularjs

How can I do something like this: $sce.trustAsResourceUrl('URL_HERE');

Globally, like in the main app's config() or run() functions so that any iFrames, img src etc that have URL_HERE will work?

Docs are rather poor at explaining this.

like image 259
Francisc Avatar asked Nov 18 '13 13:11

Francisc


People also ask

What is$ sce in Angular?

Strict Contextual Escaping (SCE) is a mode in which AngularJS constrains bindings to only render trusted values. Its goal is to assist in writing code in a way that (a) is secure by default, and (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier.

What is trustAsResourceUrl?

trustAsResourceUrl returns a special wrapper object for the external URL to mark the URL as trusted.

What is SCE trustAsHtml in AngularJS?

The ng-controller uses $sce (Strict Contextual Escaping) service which is used to mark the HTML as trusted using the trustAsHtml method. Note: Unless the HTML content is trusted using the $sce service, it will not be displayed using ng-bind-html directive.

What is trustAsHtml?

trustAsHtml() produces a string that is safe to use with ng-bind-html" seems catastrophically misleading and incorrect. It yields a proxy for sanitisation bypass, and the result could be completely unsafe to use with ng-bind-html.


2 Answers

You could use a filter. These are available globally.

angular.module('myApp')   .filter('trustUrl', function ($sce) {     return function(url) {       return $sce.trustAsResourceUrl(url);     };   }); 
<img ng-src={{ imageHref | trustUrl }}"> 
like image 126
Tom Spencer Avatar answered Sep 18 '22 07:09

Tom Spencer


I just read your comment from the previous answer. Not sure if you found a solution yet. Seems you are looking for a whitelist type of thing. I recently found this out that there's a whitelist function for $sce.

Taken from the AngularJS docs for $sceDelegateProvider:

angular.module('myApp', []).config(function($sceDelegateProvider) {  $sceDelegateProvider.resourceUrlWhitelist([    // Allow same origin resource loads.    'self',    // Allow loading from our assets domain.  Notice the difference between * and **.    'http://srv*.assets.example.com/**']);  }) 

With this you can do string interpolation in iframes like this:

<iframe ng-src="{{ 'http://srv1.assets.example.com/' + url_asset }}"></iframe> 
like image 31
chriz Avatar answered Sep 18 '22 07:09

chriz