javascript / intermediate
Snippet
Safely Bypassing Trusted Resource URLs via Angular DomSanitizer
Angular automatically treats all values as untrusted when binding to sensitive DOM contexts like iframe source URLs to protect against Cross-Site Scripting (XSS). When loading dynamically composed URLs into embedded frames, you can sanitize parameters and explicitly mark the string as a SafeResourceUrl using the DomSanitizer service. This signals Angular's template compiler that the resource is safe to render.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { Component, inject } from '@angular/core';import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';@Component({selector: 'app-video-frame',template: `<iframe [src]="trustedUrl" width="560" height="315"></iframe>`})export class VideoFrameComponent {private readonly sanitizer = inject(DomSanitizer);public trustedUrl: SafeResourceUrl | null = null;public setVideoSource(rawVideoId: string): void {const sanitizedId = encodeURIComponent(rawVideoId.trim());const targetUrl = `https://www.youtube-nocookie.com/embed/${sanitizedId}`;this.trustedUrl = this.sanitizer.bypassSecurityTrustResourceUrl(targetUrl);}}
angular
Breakdown
1
private readonly sanitizer = inject(DomSanitizer);
Injects the DomSanitizer dependency into the component instance using the inject function.
2
public trustedUrl: SafeResourceUrl | null = null;
Declares the property typed as SafeResourceUrl, which prevents Angular's template binding from throwing security errors.
3
const sanitizedId = encodeURIComponent(rawVideoId.trim());
Sanitizes dynamic input parameters to ensure no malicious URL tampering occurs before building the final URL.
4
this.trustedUrl = this.sanitizer.bypassSecurityTrustResourceUrl(targetUrl);
Explicitly instructs Angular to trust this specific URL for use as an embedded resource.