在使用 `
// 當前頁面在 iframe 中,想讓頂層頁面跳轉
window.top.location.href = 'https://example.com/welcome';
// 或使用 replace 不保留歷史
window.top.location.replace('https://example.com/welcome');
// 父頁面有 或
// 當前在 frameA,要導向 frameB
window.parent.frames['frameB'].location.href = 'page.html';
// 在 iframe 內部載入新頁面
window.location.href = 'new-page.html';
// 或
window.location.assign('new-page.html');
// JSP 頁面輸出 JS 導向
<script>
window.parent.location.href = '<%= request.getContextPath() %>/welcome';
</script>
// Java Servlet 直接輸出
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.write("");
out.flush();
**同源策略**禁止存取不同源(協定/域名/埠)框架的 `location`、`document` 等屬性。
// 父頁面
window.addEventListener('message', e => {
if (e.origin !== 'https://trusted-child.com') return;
if (e.data.type === 'NAVIGATE') {
window.location.href = e.data.url;
}
});
// 子頁面(iframe 內)
window.parent.postMessage({ type: 'NAVIGATE', url: '/dashboard' }, 'https://parent.com');
同一主域名下不同子域名可設定 `document.domain = 'example.com'` 互通,但**無法跨不同主域名**,且現代瀏覽器正逐步移除此功能。
// 父頁面載入 iframe 時帶參數
// 子頁面完成操作後導向 returnUrl
window.top.location.href = new URLSearchParams(location.search).get('returnUrl');
| 問題 | 原因 | 解決 |
|---|---|---|
| 「拒絕存取」錯誤 | 跨域存取 frame.location | 改用 postMessage |
| 導向後頁面空白 | X-Frame-Options: DENY / SAMEORIGIN | 伺服器設定允許嵌入或改用跳出框架導向 |
| history.back() 失效 | iframe 內導向不影響父頁歷史 | 使用 postMessage 通知父頁面處理歷史 |
| 多層 iframe 導向錯誤 | parent.parent... 鏈路錯誤 | 統一用 window.top 或 postMessage 廣播 |
掌握框架導向細節與跨域通訊標準,能讓複雜多視窗應用穩健運作。