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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response