0

Having an iframe like this:

<iframe class="e2e-iframe-trusted-src"  height="480" width="500" src={{trailer.address}}> 
</iframe>

I'am getting the following error:

"ERROR Error: unsafe value used in a resource URL context"

nb:trailer.address is retrieving the url.

kidroca
  • 3,480
  • 2
  • 27
  • 44

1 Answers1

0

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

kidroca
  • 3,480
  • 2
  • 27
  • 44
  • i cant really use this method because iam using loop in component.html like --*ngFor='let trailer of trailers'-- . Need to sanitize in template itself. – AjmalPt Jan 19 '21 at 07:06
  • You can use the "Pipe Approach" to sanitize the value in the template. – kidroca Jan 19 '21 at 14:40