首页 > 解决方案 > 是否可以访问 iframe 之外的数组?

问题描述

问题是这样的:在我的主页 ( parent.html) 内,我有一个 iframe ( child.html) 和一个脚本块。在该脚本块中有一个整数数组和一个将元素添加到列表的函数。在 iframe 中有一个新函数,可以将元素添加到主文件 ( parent.html) 的列表中。

我想知道 iframe( child.html) 是否可以访问parent.html. 例子:

父.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>

错误

child.html:12 Uncaught ReferenceError: parentList is not defined
    at addValueInternal (child.html:12)
    at HTMLButtonElement.onclick (child.html:6)

标签: javascripthtmliframe

解决方案


是的。有可能的。基于从嵌入式 iframe 调用父级中定义的函数的示例。

因此,在您的情况下,您必须parent在访问数组时引用。

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

请注意,您之后可能会遇到有关跨域策略的问题。


推荐阅读