0

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>

2 Answers2

1

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.

Community
  • 1
  • 1
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
0

Yes, as long as they're on the same domain. This has been asked before on stack overflow, see this thread.

In short (from linked thread)

document.getElementById('someDiv').innerHTML = 
  top.document.getElementById('otherIframe').contentWindow.
  document.getElementById('someOtherDiv').innerHTML;
Community
  • 1
  • 1
joeyfb
  • 3,044
  • 3
  • 19
  • 25
  • Could you elaborate on how accessing a div from within the iframe using the iframe eventually allows you to alter the parent window? –  Apr 26 '15 at 04:44