为了账号安全,请及时绑定邮箱和手机立即绑定

是否可以访问 iframe 外部的数组?

是否可以访问 iframe 外部的数组?

天涯尽头无女友 2023-10-17 19:54:30
问题是这样的:在我的主页 ( 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>孩子.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)
查看完整描述

1 回答

?
蛊毒传说

TA贡献1895条经验 获得超3个赞

是的。有可能的。

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

function addValueInternal() {

  internalCount++;

  parent.parentList.push(internalCount); // here we access the reference

  console.log('child', parentList);

}

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


查看完整回答
反对 回复 2023-10-17
  • 1 回答
  • 0 关注
  • 55 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信