[Fixed] Angular 5 in safepipe get error – Required a safe ResourceURL, got a HTML

Issue

In Angular 5, I want to show a map in iFrame. I used safepipe, however, receives error in console

Required a safe ResourceURL, got a HTML

Here is the code is my .ts file:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer} from '@angular/platform-browser';

export class XXXComponent implements OnInit {
constructor(private sanitizer: DomSanitizer){}

this.mapURL = "https://www.google.com/maps/embed/v1/place?key=AIzaSyDdWRYxwcpnrJWXbsR4fmP3HwvsFlCMYPk&q=Ylistörmä+1,+02210+Espoo,+Finland&attribution_source=Google+Maps+Embed+API";
this.urlsafe = this.createSafeMap(this.mapURL);

createSafeMap(url){
   return this.sanitizer.bypassSecurityTrustHtml(url);
}

In the .html file, I did the following to show the map in iframe:

<iframe [src]="urlsafe | safe: 'html'"></iframe>

Below is the content of safe.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
    
@Pipe({
   name: 'safe'
})
export class SafePipe implements PipeTransform {
    
   constructor(protected sanitizer: DomSanitizer) {}
     
   public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
      switch (type) {
         case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
         case 'style': return this.sanitizer.bypassSecurityTrustStyle(value);
         case 'script': return this.sanitizer.bypassSecurityTrustScript(value);
         case 'url': return this.sanitizer.bypassSecurityTrustUrl(value);
         case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value);
         default: throw new Error(`Invalid safe type specified: ${type}`);
      }
   }
}

Solution

In order to use url safely you simply need to write safe pipe with resourceUrl parameter and throw away your urlsafe wrapper:

[src]="mapURL | safe: 'resourceUrl'"

Leave a Reply

(*) Required, Your email will not be published