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:

Article Contents

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="https://domain.com/index.html></iframe>

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

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: https://developer.mozilla.org/en-US/docs/DOM/window.frameElement
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: https://developer.mozilla.org/en-US/docs/DOM/window.postMessage

To send a message using window.postMessage method:

parentWindow.postMessage('Hello from iframe!', 'https://domain.com');

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

window.addEventListener('message', function(e) {
console.log(e.data);
//do stuff
});

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

See also  Knex.js Tutorial | A Complete Guide

Leave a Comment