43

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.

Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64
Francisc
  • 77,430
  • 63
  • 180
  • 276
  • For those (like me) who want to do the same thing in an up-to-date Angular 9: https://stackoverflow.com/questions/37927657/img-unsafe-value-used-in-a-resource-url-context – Daniel Alder Feb 25 '20 at 23:08

4 Answers4

74

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 }}">
Tom Spencer
  • 7,816
  • 4
  • 54
  • 50
55

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>
Ryan Allen
  • 5,414
  • 4
  • 26
  • 33
chriz
  • 1,826
  • 2
  • 24
  • 28
  • 5
    Still wondering what is actually the difference between * and **... :( – GôTô Dec 27 '16 at 09:45
  • * says the contents of current directory and /** says the contents of this directory and all of its sub-directories downwards – ahmednawazbutt Sep 22 '17 at 09:40
  • 2
    @ahmednawazbutt that is incorrect. The angular source code for the sce provider is here: https://github.com/angular/angular.js/blob/0822d34b10ea0371c260c80a1486a4d508ea5a91/src/ng/sce.js#L621 and says * matches zero or more occurrences of any character other than one of the following 6 characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. ** matches zero or more occurrences of *any* character. As such, it's not appropriate for use in a scheme, domain, etc. as it would match too much. – Kiley Naro Jan 12 '18 at 15:14
7

I also liked the filter solution; however, it didn't work for me until I injected $sce properly...

app.filter('trustUrl', ['$sce', function ($sce) {
  return function(url) {
    return $sce.trustAsResourceUrl(url);
  };
}]);
mandrewsan
  • 93
  • 1
  • 5
1

I use for my videos stored on filesystem:

app.config( [
    '$sceDelegateProvider',
    function($sceDelegateProvider)
    {
        $sceDelegateProvider.resourceUrlWhitelist(['self','filesystem:**']); 
    }
]);
Jarda Pavlíček
  • 1,636
  • 17
  • 16