Access DOM element in another page

I am trying to use postmessage to have an embedded iframe in my app, communicate with the content on my server that is being embedded. To do this I need to be able to access the .contentWindow of the iframe element and the iframe is in a modal and I need to be able to access it from anywhere in my app.

I have a couple of questions:

  1. I know it is not good practice to access the DOM directly, is there any way to access the iframe’s contentWindow without accessing the DOM directly?

  2. In Ionic v1 I was able to access the contentWindow of the iframe by simply using document.getElementById(‘name_of_iframe_element’).contentWindow. This doesnt work in V2. I know I can use ViewChild to access an element in the same page, but how do I do this to get an element on a different page?

Thanks for the help.

I think using iFrames in Ionic is a bad idea. Sorry.

Iframes, in fact doesn’t work with Ionic (forbidden if another domain like otherdomain.com).

Thanks for the responses. I actually have the IFrame working, i just need to be able to access the iframe element when the content changes (from another page).

Use DI to access the iframe. Create global service. Declare a variable for iframe: any or HTMLElement. Get iframe with @ViewChild and set the variable. Use service to access iframe in any page.

But if document.getElementById(‘name_of_iframe_element’).contentWindow didn’t work, iframe doesn’t exist in app. You can’t use the DI method too.

Thanks for the help got it working! I was doing what you mentioned @hmtylmz but I had an *ngIf on the element that I think was causing it to tear down the element and render the linked variable invalid. I changed the *ngIf to a [hidden] and it all works! thanks again :slight_smile: