HappyCoder
HappyCoder

Reputation: 6155

Error trying to get window of iFrame

I am attempting to get the window of an iFrame using the following code:

  var frameWindow = document.getElementById("loginframe");
  var iWindow = frameWindow.contentWindow;

Unfortunately, I keep getting the following error:

Property 'contentWindow' does not exist on type 'HTMLElement'.)

As you can see in the screenshot below, "contentWindow" is highlighted in red which is an error...

enter image description here

I have tried casting:

  let map = document.getElementById("loginframe") as HTMLObjectElement;
  let insideDoc = map.contentDocument; 

But this does not work either...

Is this something to do with angular libraries that perhaps I need to include?

Upvotes: 0

Views: 1752

Answers (1)

Owain van Brakel
Owain van Brakel

Reputation: 3349

First of all you shouldn't select a DOM element like that you should use a viewChild to do that.

<iframe src="urlHere" #loginframe ></iframe>

Then you can use it in your TypeScript code like this:

@ViewChild('loginframe') loginframe: ElementRef;

After that you can select the element like this: (Note: you should cast it to a HTMLIFrameElement)

const win = (<HTMLIFrameElement> this.loginframe).nativeElement.contentWindow;

Here is a fully working plnkr! (open your console to see the output)

https://embed.plnkr.co/kicS6o8QlOEcXyMKNjFi/

Upvotes: 1

Related Questions