在 JSP 頁面嵌入 `
<iframe id="agentFrame" name="agentFrame" src="" width="0" height="0" style="display:none;"></iframe>
<script type="text/javascript">
function sethash() {
// 1. 取得父頁面文件完整高度
var hashH = document.documentElement.scrollHeight;
// 2. 目標 iframe 頁面 (同域或子域)
var urlC = "/test.jsp";
// 3. 將高度編碼進 hash,觸發 iframe 載入
document.getElementById("agentFrame").src = urlC + "#" + hashH;
}
// 頁面載入完成後執行
window.onload = sethash;
</script>
<%@ page contentType="text/html;charset=GBK" language="java" %>
<script>
function pseth() {
// 1. 取得父頁面中真正顯示內容的 iframe 元素 (假設 id='infoFrame')
var iObj = parent.parent.document.getElementById('infoFrame');
// 2. 從 agentFrame 的 location.hash 解析高度
// 注意:此處存取的是 agentFrame 的 location,非當前 test.jsp
var iObjH = parent.parent.frames["infoFrame"].frames["agentFrame"].location.hash;
// 3. 格式:#1200 → 分割取得數值
var height = iObjH.split("#")[1] + "px";
// 4. 套用高度
iObj.style.height = height;
}
window.onload = pseth;
</script>
| 項目 | 說明 |
|---|---|
| iframe 隱藏 | `agentFrame` 設為 `width=0 height=0 display:none`,僅作為傳遞通道,不顯示內容。 |
| 雙層 iframe 結構 | 範例假設結構:`main.jsp` → `infoFrame` (顯示用) → `agentFrame` (傳遞用)。實際專案請依實際 DOM 階層調整 `parent.parent` 層數。 |
| 同源策略 | 父頁面與 `test.jsp` **必須同域** (或透過 `document.domain` 設定為同一主域),否則無法存取 `parent.parent.document`。跨域請改用 `postMessage` API。 |
| 時機 | 父頁面 `window.onload` 確保文件高度已穩定;`test.jsp` `window.onload` 確保 hash 已附加完成。 |
| 動態內容 | 若 iframe 內容會動態變化 (AJAX 載入、摺疊展開),需在內容變更後重新呼叫 `pseth()` 或改用 `MutationObserver` 監聽高度變化並 `postMessage` 通知父頁面。 |
HTML5 `postMessage` 提供安全跨域通訊,不依賴 hash hack,支援跨域、更清晰:
<iframe id="contentFrame" src="/child.jsp" onload="iframeLoaded()"></iframe>
<script>
function iframeLoaded() {
// 監聽子頁面訊息
window.addEventListener("message", function(e) {
// 安全性:驗證來源
if (e.origin !== "https://your-trusted-domain.com") return;
if (e.data && e.data.type === "resize" && e.data.height) {
document.getElementById("contentFrame").style.height = e.data.height + "px";
}
});
}
</script>
<script>
function notifyHeight() {
var height = document.documentElement.scrollHeight;
// 發送給父頁面
parent.postMessage({ type: "resize", height: height }, "https://parent-domain.com");
}
// 初始載入 + 內容變動時呼叫
window.onload = notifyHeight;
// 若有動態內容,在 AJAX 完成、摺疊切換後呼叫 notifyHeight()
</script>