Javascript – Target window.opener iframe

htmliframejavascript

I can write something to an iframe like this

window.frames[0].document.write(something);

But i am trying to write something to an iframe from a opened window within the same domain. I don't know how to target that iframe. I tried something like this:

window.opener.document.getElementById("iframe").write(something);

or

window.opener.frames[0].document.write(something);

But that didn't work. Any ideas or questions about what i am trying to do?

*The iframe is on the parent window. I try to target that from the opened window

Best Answer

You need to use contentWindow property of the iframe. Try this.

Parent page

<iframe id="ifr"></iframe>

<button onclick="window.open('child.html')">Open Window</button>

Child.html page

<button onclick="writeToParentIframe()">Write to Parent Iframe</button>

<script>
    function writeToParentIframe() {
        opener.document.getElementById("ifr").contentWindow.document.write("<h1>Hello World</h1>")
    }
</script>