1

So I have a page index.html with an iframe:

<iframe src="iframe1.html" width="500" height="400"></iframe>

In iframe1.html I have another nested iframe:

<iframe src="iframe2.html" width="500" height="400"></iframe>

In iframe2.html I have this code:

<script>
window.onload = function() {
    document.getElementById('change-color').onclick = function() {
        window.parent.document.body.style.backgroundColor = "red";
        return false;
    };
}
</script>

<a href="" id="change-color">Change Color</a>

What happens now when you click the "change color" link is the iframe's parent page iframe1.html gets a red background color. Instead I want parent's parent page index.html to get the color change. How to access that?

  • Maybe `window.parent.parent.document.body.style.backgroundColor`? – Barmar Mar 16 '17 at 19:57
  • @Barmar on man that did it thanks! I was trying variations but missed that one. If you answer I'll accept. –  Mar 16 '17 at 19:58
  • 1
    You can use window.parent.parent or window.top Related: http://stackoverflow.com/questions/11313045/when-to-use-window-opener-window-parent-window-top – airos Mar 16 '17 at 20:01

1 Answers1

3

Use window.parent.parent to get the grandparent window. So you want:

window.parent.parent.document.body.style.backgroundColor = "red";

And if you want the top-most parent, no matter how many levels deep you are, you can use window.top. See

Find most upper parent window with javascript

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612