Ayyash
Ayyash

Reputation: 4399

Angular2: making an iframe src safe using a directive

I am trying to apply a sanitized src attribute to an iframe, directly it works fine, but when putting it all in an attribute directive, it refuses to play ball. Here is the directive code, and the error message that appears

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


@Directive({
    selector: '[resume]'
})
export class ResumeDirective implements OnInit {

    @Input('resume') inputLink: string;

    constructor(private _sanitizer: DomSanitizer, private el: ElementRef, private render: Renderer) {

    }

    ngOnInit(): void {
        let _url: string = this.inputLink + '#zoom=100';

        let resumeUrl: SafeResourceUrl = this._sanitizer.bypassSecurityTrustResourceUrl(_url);

        // this.el.nativeElement.src = resumeUrl.toString(); // same result
        this.render.setElementProperty(this.el.nativeElement, 'src', _url);
       // using 'srcdoc' or setElementAttribute brings same results
     }
}

I get error: SafeValue must use [property]=binding: /theurl/x.pdf#zoom=100 (see http://g.co/ng/security#xss)

Upvotes: 1

Views: 1081

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657268

You can try @HostBinding() - not sure if this will work though

@Directive({
    selector: '[resume]'
})
export class ResumeDirective implements OnInit {

    @Input('resume') inputLink: string;

    constructor(private _sanitizer: DomSanitizer, private el: ElementRef, private render: Renderer) {

    }

    @HostBinding('src')
    resumeUrl:any;

    ngOnInit(): void {
        let _url: string = this.inputLink + '#zoom=100';

        this.resumeUrl = this._sanitizer.bypassSecurityTrustResourceUrl(_url);
     }
}

this.render.setElementProperty doesn't care about sanitized values, it just calles to DOM APIs and passes the sanitized value as-is.

Upvotes: 2

Related Questions