213

I am working on a tutorial involving the setting of an iframe src attribute:

<iframe width="100%" height="300" src="{{video.url}}"></iframe>

This throws an exception:

Error: unsafe value used in a resource URL context
at DomSanitizationServiceImpl.sanitize...

I have already tried using bindings with [src] with no success.

11 Answers 11

433

Update v8

Below answers work but exposes your application to XSS security risks!. Instead of using this.domSanitizer.bypassSecurityTrustResourceUrl(url), it is recommended to use this.domSanitizer.sanitize(SecurityContext.URL, url)

Update

For RC.6^ version use DomSanitizer

Plunker

And a good option is using pure pipe for that:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer} from '@angular/platform-browser';

@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
  constructor(private domSanitizer: DomSanitizer) {}
  transform(url) {
    return this.domSanitizer.bypassSecurityTrustResourceUrl(url);
  }
} 

remember to add your new SafePipe to the declarations array of the AppModule. (as seen on documentation)

@NgModule({
   declarations : [
     ...
     SafePipe
   ],
})

html

<iframe width="100%" height="300" [src]="url | safe"></iframe>

Plunker

If you use embed tag this might be interesting for you:


Old version RC.5

You can leverage DomSanitizationService like this:

export class YourComponent {
  url: SafeResourceUrl;
  constructor(domSanitizationService: DomSanitizationService) {
    this.url = domSanitizer.bypassSecurityTrustResourceUrl('your url');
  }
}

And then bind to url in your template:

<iframe width="100%" height="300" [src]="url"></iframe>

Don't forget to add the following imports:

import { SafeResourceUrl, DomSanitizationService } from '@angular/platform-browser';

Plunker sample

20
  • 1
    @FugueWeb That's because ionic2 is using angular RC4 today. github.com/driftyco/ionic/blob/master/…
    – yurzui
    Sep 24, 2016 at 16:56
  • 2
    I am using Ionic2. I declare a pipe Pipe({ name: 'safe' }) export class SafePipe implements PipeTransform { constructor(private sanitizer: DomSanitizer) {} transform(url): any { return this.sanitizer.bypassSecurityTrustResourceUrl(url); } } and in template I call <iframe width="100%" height="315" src="{{url}} | safe" frameborder="0" allowfullscreen></iframe>. But it doesn't work with error 'unsafe value'. Please help Oct 2, 2016 at 12:06
  • 1
    @Insane Rose i guess it should be [src]="url | safe" Just remove brackets
    – yurzui
    Oct 2, 2016 at 12:26
  • 9
    @yurzui I followed your recommendation for the updated v8. However when I use this.sanitizer.sanitize(SecurityContext.URL, url) I'm getting an error "ERROR Error: unsafe value used in a resource URL context" I I change it to this.sanitizer.bypassSecurityTrustResourceUrl(url) works fine. Any idea what can be wrong?
    – Kosmonaft
    Jul 22, 2019 at 7:15
  • 6
    this.sanitizer.sanitize(SecurityContext.URL, url) doesn't work and this.sanitizer.bypassSecurityTrustResourceUrl(url) works but raises high security vulnerability issue in static code analysis, which prevents me from moving this to production. Need a way to fix this
    – cjkumaresh
    Oct 16, 2019 at 12:00
42

This one works for me.

import { Component,Input,OnInit} from '@angular/core';
import {DomSanitizer,SafeResourceUrl,} from '@angular/platform-browser';

@Component({
    moduleId: module.id,
    selector: 'player',
    templateUrl: './player.component.html',
    styleUrls:['./player.component.scss'],
    
})
export class PlayerComponent implements OnInit{
    @Input()
    id:string; 
    url: SafeResourceUrl;
    constructor (public sanitizer:DomSanitizer) {
    }
    ngOnInit() {
        this.url = this.sanitizer.bypassSecurityTrustResourceUrl(this.id);      
    }
}
3
  • This approach works for me since I use this in 1 place. Otherwise the pipe approach is better. May 23, 2018 at 12:30
  • @Pang How it work? i have the same issue i want to add my parameter in url i am using these code "@Input() parameterForFB: number = this.selectedStudent.schoolId url: string = "designs.mydeievents.com/jq-3d-flip-book/index.html?id=${parameterForFB}"; urlSafe: SafeResourceUrl;" but not working face issue in parameter. Sep 27, 2019 at 10:10
  • Thank you. This is the only way I could get this to work, none of the examples with pipe worked. Mar 16, 2021 at 12:40
28

This works me to Angular 5.2.0

fileName.Component.ts

import { Component, OnInit, Input } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

@Component({
  selector: 'app-sample',
  templateUrl: './fileName.component.html',
  styleUrls: ['./fileName.component.scss']
})

export class FileName implements OnInit {
  @Input()
  url: string = "https://www.mmlpqtpkasjdashdjahd.com";
  urlSafe: SafeResourceUrl;

  constructor(public sanitizer: DomSanitizer) { }

  ngOnInit() {
    this.urlSafe= this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
  }

}

fileName.Component.html

<iframe width="100%" height="100%" frameBorder="0" [src]="urlSafe"></iframe>

thats all folks!!!

2
  • 2
    Tried this. It works but the console keeps throwing the error Error: unsafe value used in a resource URL context
    – Enrico
    Oct 2, 2020 at 14:32
  • urlSafe can be defined as follows. urlSafe: SafeResourceUrl | undefined; urlSafe!: SafeResourceUrl; Mar 8 at 14:40
7
constructor(
 public sanitizer: DomSanitizer, ) {

 }

I had been struggling for 4 hours. the problem was in img tag. When you use square bracket to 'src' ex: [src]. you can not use this angular expression {{}}. you just give directly from an object example below. if you give angular expression {{}}. you will get interpolation error.

  1. first i used ngFor to iterate the countries

    *ngFor="let country of countries"
    
  2. second you put this in the img tag. this is it.

    <img [src]="sanitizer.bypassSecurityTrustResourceUrl(country.flag)"
    height="20" width="20" alt=""/>
    
1
  • 1
    Be aware that putting function call inside HTML is a bad idea because it is gonna be called everytime ChangeDetector will check for changes.
    – karoluS
    Feb 12, 2019 at 21:06
6

All answers seem wrong to be honest. Using this.sanitizer.bypassSecurityTrustResourceUrl(url) only bypasses the security and treats the url as a SafeResourceUrl. However, given url may still be malicious resulting in security violations. Docs say so too: https://angular.io/api/platform-browser/DomSanitizer#bypassSecurityTrustResourceUrl

A solution would be to call sanitizer first and the pass the sanitizer return value to the bypassSecurityTrustResourceUrl like this:

this.sanitizer.bypassSecurityTrustResourceUrl(this.sanitizer.sanitize(SecurityContext.URL, url))

This way you sanitize any malicious code and then bypass the security denoting this is indeed a safe url.

1
  • This is the answer that worked for me (tested with angular 13).
    – Andi
    May 4, 2022 at 9:02
4

I ran into this issue as well, but in order to use a safe pipe in my angular module, I installed the safe-pipe npm package, which you can find here. FYI, this worked in Angular 9.1.3, I haven't tried this in any other versions of Angular. Here's how you add it step by step:

  1. Install the package via npm install safe-pipe or yarn add safe-pipe. This will store a reference to it in your dependencies in the package.json file, which you should already have from starting a new Angular project.

  2. Add SafePipeModule module to NgModule.imports in your Angular module file like so:

    import { SafePipeModule } from 'safe-pipe';
    
    @NgModule({
        imports: [ SafePipeModule ]
    })
    export class AppModule { }
    
    
  3. Add the safe pipe to an element in the template for the Angular component you are importing into your NgModule this way:

<element [property]="value | safe: sanitizationType"></element>
  1. Here are some specific examples of the safePipe in an html element:
<div [style.background-image]="'url(' + pictureUrl + ')' | safe: 'style'" class="pic bg-pic"></div>
<img [src]="pictureUrl | safe: 'url'" class="pic" alt="Logo">
<iframe [src]="catVideoEmbed | safe: 'resourceUrl'" width="640" height="390"></iframe>
<pre [innerHTML]="htmlContent | safe: 'html'"></pre>

1

This works for me

I defined an id in the iframe

<iframe id="embeddedPage"></iframe>

and in the component I used this code

export class YourComponent implements OnInit {
    
  constructor() {}

  ngOnInit(): void {
    const iframe =  document.getElementById('embeddedPage') as HTMLIFrameElement;
    iframe.contentWindow.location.replace('your url');
  }

}
1
  • 2
    WARNING: This "works" because it bypasses Angular's checks / awareness, point being this is still insecure if the url can't be trusted Apr 14, 2022 at 13:08
0

I'll share this solution even if this is NOT best practice, but it happened to me once that we were not allowed to use the this.domSanitizer.bypassSecurityTrustResourceUrl(url) solution because of an automatic security warning that stopped the CI/CD pipelines.

@Component({
  template: '<iframe #iframeRef></iframe>'
})
export class UnsafeUrlBypassIframeSampleComponent implements AfterViewInit {
  @ViewChild('iframeRef') iframe: ElementRef<HTMLIFrameElement>;
  
  constructor(private renderer: Renderer2) {}
  
  ngAfterViewInit() {
    const MY_UNSAFE_URL = '/path/to/something';
    this.renderer.setProperty(this.iframe.nativeElement, 'src', MY_UNSAFE_URL);
  }
}

If it is the case that you need to bypass Angular security systems, and this will inevitably lead to vulnerabilities, it is best to do it explicitly.

0

Update V13

the url should be sanitized first, then once we know its safe we can use bypassSecurityTrustResourceUrl.

constructor(
  private readonly domSanitizer: DomSanitizer) {}

sanitize(){
url = this.domSanitizer.sanitize(SecurityContext.URL, `/test`); //sanitize first
this.url = this.domSanitizer.bypassSecurityTrustResourceUrl(url);//then bypass
}

Then bind the url in your template.

<iframe #iFrame [src]="url">
-1

I usually add separate safe pipe reusable component as following

# Add Safe Pipe

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({name: 'mySafe'})
export class SafePipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) {
    }

    public transform(url) {
        return this.sanitizer.bypassSecurityTrustResourceUrl(url);
    }
}
# then create shared pipe module as following 

import { NgModule } from '@angular/core'; 
import { SafePipe } from './safe.pipe';
@NgModule({
    declarations: [
        SafePipe
    ],
    exports: [
        SafePipe
    ]
})
export class SharedPipesModule {
}
# import shared pipe module in your native module

@NgModule({
    declarations: [],
    imports: [
        SharedPipesModule,
    ],
})
export class SupportModule {
}
<!-------------------
call your url (`trustedUrl` for me) and add `mySafe` as defined in Safe Pipe
---------------->
<div class="container-fluid" *ngIf="trustedUrl">
    <iframe [src]="trustedUrl | mySafe" align="middle" width="100%" height="800" frameborder="0"></iframe>
</div>
-9

Congratulation ! ¨^^ I have an easy & efficient solution for you, yes!

<iframe width="100%" height="300" [attr.src]="video.url"></iframe

[attr.src] instead of src "video.url" and not {{video.url}}

Great ;)

4
  • 5
    That doesn't make a difference for string values. Jul 12, 2017 at 16:03
  • 1
    it doesn't work. Getting error message unsafe value used in a resource URL context Sep 13, 2017 at 16:27
  • So, you can use the html5 video tag, but if you insist to use iframe (for many reasons;) see other solutions that use DomSanitizationService..
    – Smaillns
    Sep 19, 2017 at 11:09
  • so if you are looking for using the 'video' tag , it will be like this <video> <source [src]=video.url type="video/mp4" /> Browser not supported </video> in fact, you can use it inorder to desplay documents too .. if you have any troubles when using video tag, I'm here ;)
    – Smaillns
    Sep 19, 2017 at 11:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.