Skip to content

Instantly share code, notes, and snippets.

@MurhafSousli
Last active September 6, 2021 06:48
Embed
What would you like to do?
Angular Sanitize Html Pipe
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);
}
}
@ingaropolous
Copy link

ingaropolous commented Jan 17, 2018

Thanks, I used this as walkthrough for implement a more complex sanitize html pipe.

@juliandavidmr
Copy link

You can add types:

import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

...

transform(html: string) : SafeHtml {
  return this._sanitizer.bypassSecurityTrustHtml(html);
}

@yawnston
Copy link

yawnston commented Sep 9, 2020

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