Angular safe

Angular adds the word unsafe in front of an iOS app download link. ie the link turns from itms-services://?action=download-manifest&url=https://…manifest.plist into unsafe:itms-services://?action=download-manifest&url=https://...manifest.plist

As a result, the download link does not work. To solve it, we have to use DomSanitizer either in html or in .ts

<a [attr.href]="{{ linkVariable | safe: 'resourceUrl' }}">click me</a>

Be reminded to user attr.href instead of href=..., using href will throw a warning WARNING: sanitizing unsafe URL value SafeValue must use [property]=binding: itms-services://?action=download....

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

Ref: https://angular.io/api/platform-browser/DomSanitizer

Posted in notesTagged , ,