You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML中如何访问同级框架数据?框架顺序为何影响访问结果?

为什么框架顺序会影响跨框架DOM获取的结果?

INDEX.HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<html>
  <head>
    <title>This is a frameset with OBJECT in the HEAD</title>
  </head>
  <frameset cols="50%,50%">
    <frame src="bianca.html" name="bianca"></frame>
    <frame src="second.html" name="second"></frame>
  </frameset>
</html>

BIANCA.HTML

<!-- In bianca.html -->
<html>
  <head>
    <title>Bianca's page</title>
  </head>
  <body>
    ...the beginning of the document...
    <p id="test">
      <script type="text/javascript">
        console.log(window.parent.bianca.document.getElementById("test"));
        console.log(window.parent.second.document.getElementById("test1"));
      </script>
      ...the rest of the document...
    </p>
  </body>
</html>

SECOND.HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1 id="test1">From second frame</h1>
  </body>
</html>

控制台输出

<p id="test">...</p>
undefined

问题描述

为何第二行输出为undefined?但将index.html中框架顺序改为:

<FRAME src="second.html" id="second" name="second"></FRAME>
<FRAME src="bianca.html" id="bianca" name="bianca">

后就能得到预期的正确输出,第一种情况为何无法正常工作?

原因分析

核心问题是框架的加载顺序:

  • 浏览器会按照frameset里框架的定义顺序依次加载页面资源。
  • 第一种顺序下,先加载bianca.html,再加载second.html。当bianca.html里的同步脚本执行时,second.html还没加载完成,对应的DOM树也未构建完毕,此时调用window.parent.second.document.getElementById("test1")自然找不到目标元素,返回undefined。
  • 调整框架顺序后,second.html会先于bianca.html加载完成。当bianca.html的脚本执行时,second.html的DOM已经完全构建,因此能正常获取到test1元素。

如果要避免这种依赖加载顺序的问题,可以在bianca.html的脚本中等待父框架所有资源加载完成后再执行,比如监听父框架的load事件:

window.parent.addEventListener('load', function() {
  console.log(window.parent.second.document.getElementById("test1"));
});

内容的提问来源于stack exchange,提问作者Manishpant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 19:01:23