0

I'm unable to pass the URL to an iframe dynamically. I checked several sources on the Internet, but none of them worked properly.

File my-component.component.html

            <iframe
              width="100%"
              height="100%"
              src="{{ dynamicUrl }}"
              scrolling="auto"
            ></iframe>

File my-component.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
...
})
export class MyComponent implements OnInit {
  dynamicUrl =
    'https://some-website.com/app/main/dashboards/63a0846ut7gxn0035c049e4?embed=true';

  constructor() {}

  ngOnInit(): void {}
}

The frame is not loading and in console I'm getting this error:

core.mjs:7635 ERROR Error: NG0904: unsafe value used in a resource URL context

What’s the best approach?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tanzeel
  • 4,174
  • 13
  • 57
  • 110

1 Answers1

2

The error you're encountering is related to Angular's security mechanism for preventing potential cross-site scripting (XSS) attacks. By default, Angular treats dynamic values used in resource URLs, such as the src attribute of an iframe, as unsafe.

To resolve this issue, you need to explicitly mark the URL as safe using Angular's DomSanitizer.

import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

@Component({
  // ...
})
export class MyComponent implements OnInit {
  dynamicUrl: SafeResourceUrl;

  constructor(private sanitizer: DomSanitizer) {}

  ngOnInit(): void {
    const unsafeUrl = 'https://some-website.com/app/main/dashboards/63a0846ut7gxn0035c049e4?embed=true';
    this.dynamicUrl = this.sanitizer.bypassSecurityTrustResourceUrl(unsafeUrl);
  }
}

Also use property binding in [src]

<iframe
  width="100%"
  height="100%"
  [src]="dynamicUrl"
  scrolling="auto"
></iframe>

You can also make sanitizerURL pipe.

Ramesh Kumar
  • 455
  • 3
  • 10
  • what are you saying? This is a very common problem that every Angular developer has faced at some point. There are a few solutions available online, and you should be able to find one that works for you by searching Google. – Ramesh Kumar Jun 26 '23 at 14:03
  • This answer looks like it was generated by an AI (like ChatGPT), not by an actual human being. You should be aware that [posting AI-generated output is officially **BANNED** on Stack Overflow](https://meta.stackoverflow.com/q/421831). If this answer was indeed generated by an AI, then I strongly suggest you delete it before you get yourself into even bigger trouble: **WE TAKE PLAGIARISM SERIOUSLY HERE.** Please read: [Why posting GPT and ChatGPT generated answers is not currently acceptable](https://stackoverflow.com/help/gpt-policy). – tchrist Jul 03 '23 at 21:35