Call function of the parent window from iframe window from JavaScript

You can call code of the parent window form child window.

f you open window by using iframe, you can communicate from child window with the parent.

Let’s see an example

Page1.html (Parent window)
<script>
        function HelloFromChild(name) {
            alert("Hello " + name + " , (called from child window)");
        }
    </script>
<iframe src="Page2.html" width="200"></iframe>
Page2.html (child window opened in iframe)
<script>
        function onClick() {
            parent.HelloFromChild(document.getElementById("name").value);
        }
</script>
Iframe page
<input type="text" name="name" value="techie" id="name" />
<button onclick="onClick();">Call Parent Window Function</button>

When you open Page1.html in browser you will see the output as below. Click on the button to call parent function.

When you click on the button, onClick event will be fired. onClick event will call function from parent window by using parent variable. By using parent variable you can call function from parent window.

Call function of the parent window from iframe window from JavaScript

 

Published by

Mandar Badve

Microsoft web, cloud, mobile developer

2 thoughts on “Call function of the parent window from iframe window from JavaScript”

  1. For crying out loud… why use “OnClick” for a function name? You should avoid using names that are so similar to reserved words! Secondly, why don’t you just pass the data directly into your function…

    You should never use document.getElementById(”) if you know the ID, well unless you enjoy typing forever.

    The only time you use it is when the ID is a VARIABLE (no quotes).

    Anyway, it’s a crappy example that won’t work. Oh, and always DATE your articles.

Leave a Reply

Your email address will not be published. Required fields are marked *