How to sanitize your urls in angular

Project: codeverFile: backup-bookmarks-dialog.component.ts

On Codever you can backup your bookmarks and snippets. When backing up you are presented a dialog where you can choose to display the items in browser. For that we use a blob URL we know for sure it is safe.

To not get the unsafe prefix in your generated html I use the DomSanitizer and its method bypassSecurityTrustUrl as shown in the example below:

export class BackupBookmarksDialogComponent implements OnInit {

  backupType: string; // 'bookmarks' | 'snippets';
  blobUrl: any;
  sanitizedBlobUrl: any;
  filename: string;

  constructor(
    private dialogRef: MatDialogRef<BackupBookmarksDialogComponent>,
    private router: Router,
    @Inject(MAT_DIALOG_DATA) data,
    private sanitizer: DomSanitizer
  ) 
    this.sanitizedBlobUrl = 
    this.sanitizer.bypassSecurityTrustUrl(data.blobUrl);
    this.blobUrl = data.blobUrl;
    this.backupType = data.backupType;
    const currentDate = new Date();
    this.filename = `$this.backupType_$currentDate.toISOString().json`;
  

In the html component the sanitizedBlogUrl is injected in the href attribute of the a html element

  <a [href]="sanitizedBlobUrl" [download]="filename" type="button" class="btn btn-primary btn-sm mr-2" (click)="download()"><i class="fas fa-download"></i> Download
  </a>


Reference –

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

Shared with ❤️ from Codever. Use 👉 copy to mine functionality to add it to your personal snippets collection.


Source link