How to talk to the parent page from an iframe

Created April 3, 2012

Somtimes you need a way to communicate with an iframe. Talking directly to the iframe can be done by sending parameters via the src URL, but what if you need a simple way to pass something from an iframe to the parent page? Well, the simplest way to do this would be to call a javascript function that lives in the parent page. To access the parent page, you will use the 'parent' object inside javascript of your iframe.

As an example, here is what your parent page might look like

<script type="text/javascript">
    function alert_me(string)
    <iframe src="my_iframe.html"></iframe>
</pre><p>Now, inside of your iframe html, you could simply do the following to call the parent function within your iframe (my_iframe.html):</p>
<pre lang="HTML">
    <script type="text/javascript">
        parent.alert_me('hello there!');

Now, when the iframe is called it will call the parent function alert_me, additionally you can feel free to have the parent function called during an event, like a button click or even a key press. Anyway, it's very simple, hope someone can find this useful ;)