Access parent iframe with postMessage

less than 1 minute read

Rarely someone would need to use postMessage across nested iframes in cross domain scenario, but I came across this the other day:

<iframe src="//www.example.com/" name="www">
    <!-- nested body -->
    <iframe src="//foo.example.com/" name="foo">
        <!-- another nested body -->
        <iframe src="//nested.example.com/" name="nested">
            <script>
                // I want to postMessage to foo.example.com
            </script>
        </iframe>
    </iframe>
</iframe>

You can access the parent iframe just as if it wasn’t on a different subdomain. But the caveat is that the parent’s parent frame cannot be accessed.

// within iframe[name=nested]
parent.postMessage("some message", "https://foo.example.com");

If access to iframe[name=www] is necessary, and is the topmost frame, messages can be sent with:

// within iframe[name=nested]
top.postMessage("some message", "https://www.example.com");

Leave a Comment