简体   繁体   中英

How to get the parent iframe's parent iframe using JavaScript?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM