How to set `. But it doesn't work with error 'unsafe value'. Please help – Insane Rose Oct 02 '16 at 12:06

  • @Insane Rose what version ionic2 do you use? – yurzui Oct 02 '16 at 12:17
  • @yurzui I use 2.1.0 When I call `[src]="'https://www.youtube.com/embed/CM6rVEAAQ3k' | safe" ` It works normally. But if ` [src]="{{url}} | safe" ` with url='link youtube' . It doesn't work. I can't see – Insane Rose Oct 02 '16 at 12:24
  • 1
    @Insane Rose i guess it should be `[src]="url | safe"` Just remove brackets – yurzui Oct 02 '16 at 12:26
  • > Angular 2.2.1 ``` constructor(sanitizer: DomSanitizer) { this.url = sanitizer.bypassSecurityTrustResourceUrl('your url here'); } ``` – ErvTheDev Dec 15 '16 at 09:35
  • I would like to add that not all webapps are iframe friendly and any errors that say that X-Frame-Headers is `sameorigin` mean that the webapp does not want to be embedded as an iframe and are not an issue with angular2. – vamsiampolu Mar 10 '17 at 04:42
  • Interestingly I was able to embed my YouTube video iframe today with no issues (ie. I did not need this solution) - I am using ng4. A bit off topic but if you want a responsive video width here is a great solution - https://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php – Rodney Apr 05 '17 at 17:41
  • 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 '19 at 07: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 '19 at 12:00
  • 1
    Doing `this.sanitizer.sanitize(SecurityContext.URL, url)` alone doesn't work it seems, so what I do is call `sanitize` and then `bypassSecurityTrustResourceUrl` on the result, unsure if that's a good way to do it but that works at least and seems safe enough. – Sahar Atias Jan 31 '20 at 17:05
  • Your plunker has a case mismatch in pdfURL/pdfUrl identifiers. – Anton Duzenko Jun 05 '20 at 07:10
  • this.sanitizer.bypassSecurityTrustResourceUrl(url) that makes the code vulnerable and i can not move it to production. Any better approach for this? – Mohit Sep 01 '20 at 05:12
  • I was assigning the src wrongly like src="url | safe" so it was not working and corrected it to [src]="url | safe", then the iframe in teh component started displaying the url. Thanks. – Rajkumar M Nov 28 '20 at 09:24
  • @Mohit did you find the way to resolve the code vulnerable – zhangjianrencai Jul 06 '21 at 10:19
  • @zhangjianrencai - actually i have used the same code, in production we have https so it won't cause any issue – Mohit Jul 07 '21 at 07:52
  • 1
    @yurzui May I know what is the issue with using `bypassSecurityTrustResourceUrl` method? – Vimal Patel Dec 31 '21 at 07:10
  • what if I've an empty src in the load of the component, as the data is dinamically charged by workflow of the user? – Leandro Bardelli Jul 21 '22 at 16:15
  • Joining the party late, but the chrome issue with embed tag is not only limited to chrome, it is in edge also – ispostback Nov 11 '22 at 10:03
  • 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);      
        }
    }
    
    Pang
    • 9,564
    • 146
    • 81
    • 122
    vikvincer
    • 639
    • 6
    • 10
    • This approach works for me since I use this in 1 place. Otherwise the pipe approach is better. – Narek Tootikian May 23 '18 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 = "http://designs.mydeievents.com/jq-3d-flip-book/index.html?id=${parameterForFB}"; urlSafe: SafeResourceUrl;" but not working face issue in parameter. – Arjun Walmiki Sep 27 '19 at 10:10
    • Thank you. This is the only way I could get this to work, none of the examples with pipe worked. – Mark Hagers Mar 16 '21 at 12:40
    29

    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!!!

    Lrodriguez84
    • 714
    • 7
    • 8
    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=""/>
      
    Kumaresan Perumal
    • 1,926
    • 2
    • 29
    • 35
    • 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 '19 at 21:06
    7

    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.

    tiempo
    • 121
    • 2
    • 14
    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>
    
    
    LRitter
    • 149
    • 2
    • 11
    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');
      }
    
    }
    
    Josef
    • 2,869
    • 2
    • 22
    • 23
    • 2
      WARNING: This "works" because it bypasses Angular's checks / awareness, point being this is still insecure if the `url` can't be trusted – Darren Shewry Apr 14 '22 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.

    Dylanbob211
    • 1,064
    • 1
    • 10
    • 15
    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">
    
    Shandy223
    • 1
    • 4
    -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>
    
    Janki
    • 191
    • 1
    • 8
    -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 ;)

    Smaillns
    • 2,540
    • 1
    • 28
    • 40
    • 5
      That doesn't make a difference for string values. – Günter Zöchbauer Jul 12 '17 at 16:03
    • 1
      it doesn't work. Getting error message `unsafe value used in a resource URL context` – Derek Liang Sep 13 '17 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 '17 at 11:09
    • so if you are looking for using the 'video' tag , it will be like this `` _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 '17 at 11:17