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

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.

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.

You will find the complete code on my GitHub safepipeURL.