call js function iframe parent

How to Call Parent Window Function from IFrame

IFrames allow you to embed content of other web pages on a given page. They are useful in adding content and features without rewriting code. But sometimes, you may need to call parent window function from IFrame. In this article, we will learn how to call parent window function from IFrame.


How to Call Parent Window Function from IFrame

Let us say you have the following IFrame.

<script>
    function myFunc()
    {
        alert("hello world");
    }
</script>

<iframe id="myFrame">
    <a id='myLink' onclick="myFunc();" href="#">Click Me</a>
</iframe>

As you can see above, the anchor link with id=myLink is embedded inside IFrame with id=myFrame. The parent web page contains a JS function myFunc(). We have defined the anchor link in such a way as to call myFunc() when it is clicked.

But it will not work since the anchor link is in an IFrame while the function myFunc() is in its parent page. So how do we proceed in this case? The solution is to call parent.myFunc() or window.parent.myFunc() instead of calling just myFunc().

<a onclick="parent.myFunc();" href="#" >Click Me</a>

When you call only myFunc(), JS will look for the function in the namespace of web page where anchor tag is defined, that is inside the IFrame, and not its parent page.

When you prefix it with ‘parent.’, only then JS will look for the function in the namespace of parent page.

window.parent returns a reference to parent of current window or subframe. When a window is loaded in an <iframe>, <object>, or <frame>, its parent is the window with element embedding the window. If a window does not have parent, window.parent will return a reference to itself.

In this article, we have learnt how to call parent window function from IFrame, by slightly adjusting the way we call the function.

Also read:

How to Get Cookie By Name in JavaScript
How to Find Max Value of Attribute in Array
How to Get Last Item of JS Array
How to Check if Variable is Object in JS
How to Check if Browser Tab is Active in JS

Leave a Reply

Your email address will not be published.