Angular Sanitize Html Pipe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Pipe, PipeTransform } from '@angular/core'; | |
import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; | |
@Pipe({ | |
name: 'sanitizeHtml' | |
}) | |
export class HtmlSanitizerPipe implements PipeTransform { | |
constructor(private sanitizer: DomSanitizer) { | |
} | |
transform(value: string): SafeHtml { | |
return this.sanitizer.bypassSecurityTrustHtml(value); | |
} | |
} |
You can add types:
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
...
transform(html: string) : SafeHtml {
return this._sanitizer.bypassSecurityTrustHtml(html);
}
To anyone reading this - this pipe DOES NOT SANITIZE THE HTML! If the passed HTML contains script tags inserted by an attacker, you just got your site successfully attacked by XSS! What this pipe does is it tells Angular to trust the given value as safe, e.g. to not escape any <script> tags contained inside it for example. Only use this pipe when you are 100% sure that the input is safe! The DomSanitizer
contains a sanitize
function which can sanitize potentially dangerous HTML for you.
The documentation for the bypassSecurityTrustHtml
function has this to say: **WARNING:** calling this method with untrusted user data exposes your application to XSS security risks!
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, I used this as walkthrough for implement a more complex sanitize html pipe.