htmlangulartypescriptangular-dom-sanitizer

Angular link to localhost url


I am making an angular project and one of my links must redirect to another website. In my dev environment this is a localhost url such as locahost:4210.

Because this is an unsafe operation to angular I have tried to use a DomSanitizer to allow the use of such an url like so :

JS :

constructor(private sanitizer:DomSanitizer){ }

public sanitizeUrl(url: string) {
  return this.sanitizer.bypassSecurityTrustUrl(url);
}

HTML :

<a [href]="sanitizeUrl('localhost:4210')">My link</a>

This doesn't work as the console of my browser indicate that the protocol is unkown. Is there an other way to make this ?

Many thanks ! Kev


Solution

  • You can implement a safe pipe that facilitates the DomSanitizer like so:

    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}`);
            }
      }
    }
    

    and then use it like so:

    <a href="http://localhost:4210 | safe: 'url'">My link</a>
    

    More details here: https://medium.com/@swarnakishore/angular-safe-pipe-implementation-to-bypass-domsanitizer-stripping-out-content-c1bf0f1cc36b