在框架(frame)架構的頁面中,釐清視窗物件之間的層級關係是避免存取錯誤的關鍵。
top 永遠指向整組視窗中最外層的瀏覽器視窗。若需要從最外層開始下指令,就透過 top 存取,例如 top.someFrame.location。因為 top 代表最外層的 frameset,它能直接取用其中任何一層的子 frame。
parent 指的是「包含目前視窗的上一層視窗」。若視窗中嵌了框架,而該框架內又再嵌一層框架,第二層就能用 parent 參照到直接包含它的父框架。
Window → Parent → Frame → Document → Form,寫成存取鏈就是:
parent.frame1.document.forms[0].elements[0].value;
另外要留意:window.location 與 window.top.location 只有在單層架構下才等價;多層架構時前者仅代表目前框架,後者代表最外層。
<html>
<head>
<title>top / frame / parent 示例</title>
<script language="javaScript" type="text/javaScript">
window.location.href = "https://www.baidu.com/";
</script>
</head>
<frameset id="outFrameset" rows="150,*,150" cols="*" border="5">
<frame name="frameName1" id="frameId1" src="a.html">
<frameset id="inFrameset" cols="150,*" rows="*">
<frame name="innerFrameName1" id="innerFrameId1" src="a.html">
<frame name="innerFrameName2" id="innerFrameId2" src="a.html">
</frameset>
<frame name="frameName2" id="frameId2" src="a.html">
</frameset>
</html>
以這個結構來說,內層框架可以用 parent.innerFrameName2.location 找到兄弟框架;而從任何一層都能用 top.innerFrameName1.location 直接穿透到目標。補充一點:frameset 在 HTML5 中已被視為過時技術,新專案建議改用 iframe 搭配 postMessage 溝通。