0

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

Kevin Heirich
  • 109
  • 2
  • 12

2 Answers2

1

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

Lorraine R.
  • 1,545
  • 1
  • 14
  • 39
1

Encountered a similar issue with this, especially when you have users providing the urls. As urls can be different, some with and without https:// or http:// protocols, it would be good to manually check the url value first and then only append "//" to the URLs without "https://" and "http://" protocols. For example:

 <a [href]="sanitizeUrl(linkUrl)">Click me</a>

Then, in your component, define the sanitizeUrl function:

sanitizeUrl(url: string): string {
    if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
    }
    return '//' + url;
}

this way, you will handle all "https://", "http://" and all other URLs properly

Rufaro Muchedzi
  • 206
  • 2
  • 4