How to access a variable of iframe from parent with JavaScript?

Sometimes, we want to access a variable of iframe from parent with JavaScript.

In this article, we’ll look at how to access a variable of iframe from parent with JavaScript.

How to access a variable of iframe from parent with JavaScript?

To access a variable of iframe from parent with JavaScript, we use the contentWindow property.

For instance, we write

const check = document.getElementById("iframeid").contentWindow.a;

to select the iframe with getElementById in the parent page’s code.

And then we get the iframe’s window object with contentWindow.

Then we get the x global variable from contentWindow.

Conclusion

To access a variable of iframe from parent with JavaScript, we use the contentWindow property.