Access parent of Iframe using JavaScript (same-domain or cross-domain)

Iframe or inline frame (<iframe></iframe>) is used to embed another document within the current HTML document. Many times you want access function of a parent using an iframe and vice-versa or you want to have interactions between parent and child windows it may be of the same domain or cross-domain, today we will see, how to achieve this with examples.Let’s learn, JavaScript Interaction between Iframe and Parent.

This can be achieved in a number of ways, as listed below:


JavaScript Interaction between Iframe and Parent for same-domains

Note: assuming both parent and child are on the same domain

Method 1 : Using JS parent.document.getElementById(“frameId”) method to access parent of Iframe

<iframe id="frameAndHashing" name="frameAndHashing" src="></iframe>

Here we can do something like this: parent.document.getElementById(;

Note: name of iframe tag can be dynamic or static, depends on requirement.

Method 2 : Using JS window.frameElement() method to access parent of Iframe

MDN documentation:
it will return iframe if exists otherwise it will return null.

Note: this only works if both domains are same otherwise it will return null.

JavaScript Interaction between Iframe and Parent for cross-domains or same-domains

Using JS window.postMessage() method to access parent of Iframe

for Mozilla (MDN) documentation go here:

To send a message using window.postMessage method:

parentWindow.postMessage('Hello from iframe!', '');

you need to add event listeners in the parent to receive messages from iframe

window.addEventListener('message', function(e) {
//do stuff

Note: this method can be used in same-domain iframe also.

READ  5+ ways to shuffle an array using javascript ES6

About the author

Vithal Reddy

Vithal Reddy is a seasoned technology professional with expertise in Full Stack Web development, Micro services and Scaling infrastructure on Cloud.
More at

Leave a Comment

Adblock Detected!

Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by whitelisting our website.