Angular2:使用指令使iframe src安全

时间:2017-01-18 10:03:31

标签: javascript angular xss

我正在尝试将一个已清理的src属性应用于iframe,直接它可以正常工作,但是当将它全部放在属性指令中时,它拒绝播放球。这是指令代码和出现的错误消息

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

我收到错误:SafeValue must use [property]=binding: /theurl/x.pdf#zoom=100 (see http://g.co/ng/security#xss)

1 个答案:

答案 0 :(得分:2)

您可以尝试@HostBinding() - 不确定这是否可行

@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不关心已清理的值,它只是调用DOM API并按原样传递已清理的值。