Angular has built-in value inspection for untrusted values - Sanitization: https://angular.io/guide/security#sanitization-and-security-contexts
Trusting safe values: https://angular.io/guide/security#bypass-security-apis
Sometimes applications genuinely need to include executable code, display an <iframe>
from some URL, or construct potentially dangerous URLs.
This seems to be exactly your case
You can't use the url retrieved from mongo directly - trailer.address
. If you trust the content you can get a bypassed value which can be assigned to a src
.
Pipe Approach
Pipe
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
name: 'safeUrl'
})
export class SafeUrlPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) { }
transform(url) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
Add to module
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, SafeUrlPipe ],
bootstrap: [ App ]
})
Usage in template
<iframe class="e2e-iframe-trusted-src" height="480" width="500" [src]="trailer.address | safeUrl">
</iframe>
Component Approach
Component
// Add the sanitizer service to your component
constructor(sanitizer) {
this.sanitizer = sanitizer;
}
async fetchDataFromMongo() {
const trailer = await fetchSomehow();
// get a bypassed value, that won't trigger the error
this.iframeUrl = this.sanitizer.bypassSecurityTrustUrl(trailer.address);
}
Template
<iframe class="e2e-iframe-trusted-src" height="480" width="500" src="{{iframeUrl}}">
</iframe>
You can check the answers here for different approaches as they deal with the same issue: <img>: Unsafe value used in a resource URL context