2009-02-24 134 views
251

需要使用什麼JavaScript來從iframe重定向父窗口?從iframe動作重定向父窗口

我希望他們點擊超鏈接,使用JavaScript或任何其他方法將父窗口重定向到一個新的URL。

+4

**父**窗口本身也可以是`IFrame`。由於接受的答案解決了**頂部**窗口,所以我建議你稍微改變一下你的問題。 – 2012-10-10 19:33:13

回答

413
window.top.location.href = "http://www.example.com"; 

如前所述,將重定向父iframe中。

49
window.top.location.href = "http://example.com"; 

window.top引用框架層次結構頂部頁面的窗口對象。

+7

window.top.location.href屬性無法從iframe更新,它會拋出訪問被拒絕的錯誤。它只能在你在本地主機上測試時執行 – 2010-06-05 15:40:16

+3

@Ummar:我會補充說,當父節點的iframe具有相同的域,相同的端口(相同的源策略)時,它會起作用,當它們不同時引發訪問被拒絕異常,以防止安全漏洞 – Vimvq1987 2012-04-04 03:11:49

+4

@Ummar不是真實的,http://jsfiddle.net/ppkzS/用於證明。你可以改變window.top.location.href。你只是看不懂。在鉻中工作。 – Parris 2013-08-06 06:18:26

12

或替代是下述(使用文檔對象)

parent.document.location.href = "http://example.com"; 
+5

該解決方案是Firefox特定的。一個應該只使用`parent.location.href = ...`。 https://developer.mozilla.org/en/document.location – kay 2012-07-12 23:42:16

88

我發現<a href="..." target="_top">link</a>工程太

1

可以從iframe重定向,但不能從父級獲取信息。

1

這將解決苦難。

<script>parent.location='http://google.com';</script> 
0

嘗試在同一父使用父窗口

window.parent.window.location.href = 'http://google.com' 
-9

重定向的iframe通過iframe的:

window.parent.document.getElementById("content").src = "content.aspx?id=12"; 
1
window.top.location.href = 'index.html'; 

這將在主窗口重定向到索引頁面。 謝謝

5

@MIP是正確的,但有了更新版本的Safari,您需要添加沙盒屬性(HTML5)以重定向訪問iFrame。有幾個特定的​​值可以在它們之間添加一個空格。

參考(您需要滾動): https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe

例:

<iframe sandbox="allow-top-navigation" src="http://google.com/"></iframe> 
6

target="_parent"工作對我來說太棒了。容易和無憂無慮!

0

如果您想重定向到另一個域,而無需用戶做任何事情,你可以使用帶有屬性的鏈接:正如前文所說

target="_parent" 

,然後用:

document.getElementById('link').click(); 

讓它自動重定向。

例子:

<!DOCTYPE HTML> 

<html> 

<head> 

</head> 

<body> 

<a id="link" target="_parent" href="outsideDomain.html"></a> 

<script type="text/javascript"> 
    document.getElementById('link').click(); 
</script> 

</body> 

</html> 

注:JavaScript的點擊()命令必須來聲明的鏈接後。