Dinuda Yaggahavita
1 min readDec 1, 2020

ANGULAR ERROR: UNSAFE VALUE USED IN A RESOURCE URL CONTEXT

Ok, when you get this error you are probably trying to use url variable in you template. The most elegant way to fix this is use pipe to bypass security. In this example we will pass url variable into iframe src.

First of all we will create our pipe. We are injecting the DomSanitizer service, SecurityContext and executing the sanitize and bypassSecurityTrustResourceUrl method to sanitize and bypass security to trust the given value to be a safe style URL.

Note: calling these methods with untrusted USER DATA exposes your application to XSS security risks!

import { Pipe, PipeTransform } from ‘@angular/core’;import { DomSanitizer } from ‘@angular/platform-browser’; @Pipe({ name: ‘safe’})export class SafePipe implements PipeTransform { constructor(private sanitizer: DomSanitizer) { } transform(url) { return this.sanitizer.bypassSecurityTrustResourceUrl(url); } }

view rawsafe.pipe.ts hosted with ❤ by GitHub

Now add you pipe to app.module:

@NgModule({ imports: [ BrowserModule ], declarations: [ App, SafePipe ], bootstrap: [ App ]})

view rawapp.module.ts hosted with ❤ by GitHub

Then just use it!

<iframe [src]=”url | safe”></iframe>

view rawiframe.component.ts hosted with ❤ by GitHub

You can create pipes or implement logic for other contexts:

SecurityContext.NONE
SecurityContext.HTML
SecurityContext.STYLE
SecurityContext.SCRIPT
SecurityContext.URL
SecurityContext.RESOURCE_URL

And that’s all.

Dinuda Yaggahavita

16-year-old Full Stack Developer with over 5 years of experience in popular and timely programming languages.