Is there a way to inject javascript code from an iframe into the parent window?

advertisements

Is there a way to inject javascript from an iframe into its parent window using javascript? Both the iframe and the parent are in the same domain.

I cannot simply perform the action from the parent window after detecting changes in the iframe, due to other reasons.

example:

<div id="bar"> Hello World </div>
<iframe srcdoc="
    <html>
        <body>
            <script type="text/javascript">
                // change "bar"'s style or alter its content
            </script>
        </body>
    </html>
"></iframe>


All you need to do is use the global parent variable in the iframe, either by using window.parent or parent directly.

Example:

<div id="bar"> Hello World </div>
<iframe srcdoc="<html>
    <body>
        <script>
            window.parent.document.getElementById('bar').style.background = 'red';
        </script>
    </body>
</html>"></iframe>

So long as the iframe satisfy the Same-Origin Policy, this will work.