0 day streak
javascript / intermediate
Snippet

Preventing XSS with Context-Aware DomSanitizer Trust Methods

Angular sanitizes untrusted values bound to the DOM by default to prevent Cross-Site Scripting (XSS). When rendering trusted dynamic markup, SVG, or URLs, developers must explicitly bypass sanitization using DomSanitizer methods tailored to the specific security context.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeResourceUrl } from '@angular/platform-browser';
@Pipe({ name: 'safeContent', standalone: true })
export class SafeContentPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform(value: string, type: 'html' | 'resourceUrl'): SafeHtml | SafeResourceUrl {
switch (type) {
case 'html':
return this.sanitizer.bypassSecurityTrustHtml(value);
case 'resourceUrl':
return this.sanitizer.bypassSecurityTrustResourceUrl(value);
default:
throw new Error(`Unsupported sanitization context: ${type}`);
}
}
}
angular
Breakdown
1
constructor(private sanitizer: DomSanitizer) {}
Injects Angular's DomSanitizer service responsible for sanitizing and trusting DOM values.
2
transform(value: string, type: 'html' | 'resourceUrl'): SafeHtml | SafeResourceUrl {
Accepts an input string along with a union type to restrict transformations to valid DOM contexts.
3
return this.sanitizer.bypassSecurityTrustHtml(value);
Informs Angular that the HTML string has been vetted and is safe to bind to innerHTML without stripping tags.
4
throw new Error(`Unsupported sanitization context: ${type}`);
Guards against invalid context parameters at runtime to prevent accidental security bypasses.