1

I am working on Angular website , where

I am opening an another website through iframe ,

how can I read the url of the website opeaning in iframe ..?

I am putting my code

.html file

<iframe src="https://www.zaubacorp.com/">
  <p>Your browser does not support iframes.</p>
</iframe>

when I searched how can I read the url to website opening in iframe in Angular .

I got following suggestion in javascript How do I get the current location of an iframe?

alert(document.getElementById("myiframe").src);
document.getElementById("myiframe").src = 'http://www.google.com/';
alert(document.getElementById("myiframe").documentWindow.location.href);
Error: Permission denied to get property Location.href

but actually it is not working in Angular

Martin Schneider
  • 14,263
  • 7
  • 55
  • 58
Testing Anurag
  • 603
  • 4
  • 13
  • 26
  • Do you want the value of `src` or the value of `documentWindow.location.href`? The latter one is only possible, if the website of the iframe belongs to the same origin (domain) as your Angular website. (as it is mentioned in the top answer of your linked question) – Martin Schneider Feb 26 '19 at 17:00

2 Answers2

1

Via ViewChild you can access the iframe element and read the src.

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

@Component({
  selector: 'hello',
  templateUrl: 'hello.component.html',
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @ViewChild('iframe') iframe: ElementRef;

  ngAfterViewInit() {
    console.log(this.iframe.nativeElement.src);
  }
}

Your HTML:

<iframe #iframe src="https://www.zaubacorp.com/">
  <p>Your browser does not support iframes.</p>
</iframe>

For demo check this this stackblitz

yougeen
  • 168
  • 1
  • 14
0

You can use ViewChild as suggested in iframe inside angular2 component, Property 'contentWindow' does not exist on type 'HTMLElement'

DrFreeze
  • 137
  • 10