2014-10-30 102 views

回答

1

不幸的是,你不能直接跨越一個iframe的邊界互動,這會帶來安全風險。

一種解決方法是更改​​iframe中的url以包含#anchor值或?querystring,然後從父級讀取iframe的url。

+0

以及如何從父級讀取iframe的網址? – 2014-10-30 16:12:39

+0

你可以在iframe的DOM對象上使用'contentWindow.location.href'。例如:'var TheLocation = document.getElementById('myframe')。contentWindow.location.href;' – 2014-10-30 16:15:37

+0

你也可以從父級設置位置,所以這可以在兩個方向上工作。 – 2014-10-30 16:16:29

0

我希望你已經試過postMessage,這是一個JavaScript API,但有瀏覽器的限制。

父母頁面可以發佈這樣的消息。

var win = document.getElementById("iframe").contentWindow 

win.postMessage(
    "value", 
    "iframe-domain" 
); 

而且的iframe頁面可以收聽這樣的消息。

<script> 
function listener(event){ 
    if (event.origin !== "[parent-page-domain]") 
    return; 

// operate with event.data 
} 

if (window.addEventListener){ 
    addEventListener("message", listener, false) 
} else { 
    attachEvent("onmessage", listener) 
} 
</script> 

源 - http://javascript.info/tutorial/cross-window-messaging-with-postmessage