0

The problem is this: inside my main page (parent.html) I have an iframe (child.html) and a script block. In that script block there is a array of integers and a function that adds elements to the list. In the iframe there is a new function that adds an element to the list of the main file (parent.html).

I would like to know if it is possible for the iframe (child.html) to access this function found in parent.html. Example:

parent.html

<html>
    <head>
        <title>Parent</title>
        <script>
            var parentList = [0];
            var counter = 0;

            function addValue(){
                counter++;
                parentList.push(counter);
                console.log('parent', parentList);
            }
        </script>
    </head>
    <body>
        <button onclick="addValue()">Add Value (Parent)</button>
        <br />
        <iframe src="child.html" allowfullscreen></iframe>
    </body>
</html>

child.html

<html>
    <head>
        <title>Child</title>
    </head>
    <body>
        <button onclick="addValueInternal()">Add Value Child</button>
        <script>
            var internalCount = 0;

            function addValueInternal() {
                internalCount++;
                parentList.push(internalCount);
                console.log('child', parentList);
            }
        </script>
    </body>
</html>

The error:

child.html:12 Uncaught ReferenceError: parentList is not defined
    at addValueInternal (child.html:12)
    at HTMLButtonElement.onclick (child.html:6)
Leomar de Souza
  • 677
  • 10
  • 23

1 Answers1

1

Yes. it is possible. Based on an example calling a function defined in the parent from an embedded iframe.

So in your case, you would have to reference the parent when accessing your array.

function addValueInternal() {
  internalCount++;
  parent.parentList.push(internalCount); // here we access the reference
  console.log('child', parentList);
}

Be aware that you may encounter problems concerning the cross-origin policy afterwards.

Uchendu
  • 1,016
  • 12
  • 20