[Angular2] DOMSanitizer by Pipe

innertHTML등으로 string의 내용을 html DOM 에 바인딩 할때,  스크립트 공격 등을 방어하기 위해 Angular2는 DOMSanitizer를  제공한다.

이를 pipe형태로 간단하게 템플릿에서 사용하기 위해 아래와 같이 처리했다.

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

@Pipe({name: "safeHtml"})
export class SafeHtmlPipe implements PipeTransform {
    constructor(private sanitized: DomSanitizer) {
    }

    transform(value: string) {
        return this.sanitized.bypassSecurityTrustHtml(value);
    }
}

@Pipe({name: "safeCss"})
export class SafeCssPipe implements PipeTransform {
    constructor(private sanitized: DomSanitizer) {
    }

    transform(value: string) {
        return this.sanitized.bypassSecurityTrustStyle(value);
    }
}

@Pipe({name: "safeScript"})
export class SafeScriptPipe implements PipeTransform {
    constructor(private sanitized: DomSanitizer) {
    }

    transform(value: string) {
        return this.sanitized.bypassSecurityTrustScript(value);
    }
}

@Pipe({name: "safeResourceUrl"})
export class SafeResourceUrlPipe implements PipeTransform {
    constructor(private sanitized: DomSanitizer) {
    }

    transform(value: string) {
        return this.sanitized.bypassSecurityTrustResourceUrl(value);
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *