Angular how to solve sanitizing URL problem

I am working on a application where I have to open a mobile app. While getting data from web service and creating dynamic url with id I am getting following error in browser ‘core.js:7083 WARNING: sanitizing unsafe URL’. Because of this warning message, I was not able to to open mobile application because unsafe keywords gets added in the browser and the URL becomes ‘unsafe:appname://jointournament?id=1001’ .

In angular DomSanitizer helps in preventing Cross Site Scripting. And to preventing Cross Site Scripting the unsafe keyword is added when the page is render in the browser. To overcome this problem, Angular provide API ‘bypassSecurityTrust’ which disable the Angular’s built-in sanitization for the value passed. There are following type of bypassSecurityTrust in angular,

  • bypassSecurityTrustHtml
  • bypassSecurityTrustStyle
  • bypassSecurityTrustScript
  • bypassSecurityTrustUrl
  • bypassSecurityTrustResourceUrl




To read more the Angular DomSanitizer visit the Angular document page.

Coming back to the problem solution. I created a new Angular project with the help of Angular CLI ng new safeurls. To create dynamic URLs I created an array of type integer

urlIds = [1001, 1002, 1003, 1004, 1005];
in my app component file. To resolve the sanitizer issue I will create a pipe so that my code will be in a common place and can be reused later in the application. To create a new pipe type following command in terminal ng g p customepipe/safeurl. In the safeurl.pipe.ts file I added the below code. Import the DomSanitizer from ‘@angular/platform-browser’ library. Create the constructor method which accept DomSanitizer type variable. In the transform method it accept two arguments, value and prefix. Prefix we will pass the URL and in the value we will pass the Id. And by calling bypassSecurityTrustUrl API will mark the URL as safe.

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

@Pipe({
  name: 'safeurl'
})
export class SafeurlPipe implements PipeTransform {

  constructor(private domSanitizer: DomSanitizer) {}

  transform(value: any, prefix = '') {
    return this.domSanitizer.bypassSecurityTrustUrl(prefix + value);
  }

}

On the HTML page I added the below code. I keep the two versions of URLs. The first one is without safe pipe and you will see that browser will mark as unsafe. The second one will be safe url.

 <div *ngFor="let i of urlIds">
      <a href="appname://jointournament?id={{i}}">URLId-{{i}}</a>   ---  
      <a [href]="i | safeurl: 'appname://joinTournament?id='">URLId-{{i}}</a>
    </div>
Save 80% on select product(s) with promo code 80BJ8CR8 on Amazon.com

You will find the complete code on my GitHub safepipeURL.

Leave a Reply