Skip to content
Advertisement

Access iframe variable from parent – undefined

I want to access a variable in iframe from parent index.html.

The index.html:

<!doctype html>
<html lang="en-us">
  <head>
    <title>Test</title>
  </head>
  <body>
  <p>Test</p>
  <div>
  <iframe name="myIframe" id="test1" src="index2.html" width="100px" height="100px"></iframe>
  </div>
  <div>
    <script type="text/javascript">
        var clickParent = document.getElementById("test1").contentDocument.clicks;
        function onClickP() {
            console.log("click on parent: " + clickParent);
        };
    </script>
    <button type="button" onClick="onClickP()">Click Parent Button</button>
  </div>
  </body>
</html>

The iframe index2.html:

<!doctype html>
<html>
<head>
    <title>Clicks</title>
</head>

<body>
    <script type="text/javascript">
    var clicks = 0;
    function onClick() {
        clicks += 1;
        console.log("click counts: " + clicks)
    };
    </script>
    <button type="button" onClick="onClick()">Click Child Button</button>
</body>
</html>

In the console, the variable clickParent is “undefined”. How to fix this and make the variable clickParent = clicks?

This question is not a duplicate of Sharing global javascript variable of a page with an iframe within that page because it is the opposite. I want to access the iframe’s variable from the parent, not access parent’s variable from the child. My Question, the variable that parent accesses from iframe is “undefined”.

Any answers would be appreciated. Thank you.

Advertisement

Answer

Possibly a duplicate of this.

Declare global variables in the parent and set them in the iframe document using parent.var_name.

You can also access child vars by creating an object for the child document:

child_iframe = document.getElementById("iframe_id").contentWindow;
alert(child_iframe.var_name);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement