2015-06-22 72 views
2

使用iframe時,如何從iframe中的iframe獲取屬性的值?從iframe中獲取iframe的屬性

這裏是我的代碼:

<iframe src="slideriframe.html" name="iframe_a" customAttr="example" style="border:none"></iframe> 

這裏是我目前:

alert(window.frameElement.getAttribute('customAttr')); 

以下是錯誤:

Uncaught SecurityError: Failed to read the 'frame' property from 'Window': Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.

感謝

+0

你不能,如果iframe來自另一個域。對於其他解決方案,閱讀在SO上提供的其他解答,例如http://stackoverflow.com/questions/217776/how-to-apply-css-to-iframe – cari

+0

你看到這個錯誤的原因是因爲[同源策略](https://en.wikipedia.org/維基/同-origin_policy)。用非常簡單的話來說,這意味着你不能訪問不屬於你的代碼。有幾種方法可以放寬此政策,但您可以在我已鏈接的Wiki頁面上閱讀更多內容。 – icecub

回答

0

您需要使用postMessage API提供了一個在iFrame和它的父級之間進行通信的簡單方法。您將向父母發送消息,然後查找該值並將其他消息發回給iFrame。

要給父頁面發送消息,請按以下方式調用它。

parent.postMessage('Hello parent','http://origin-domain.com'); 

在另一個方向上,我們可以使用以下代碼將消息發送到iFrame。

var iframe = document.querySelector('iframe'); 
iframe.contentWindow.postMessage('Hello my child', 'http://remote-domain.com:8080'); 

若要接收消息,請爲消息事件創建事件查找器。

function receiveMessage(event) 
{ 
    if (event.origin !== "http://remote-domain.com:8080") 
    return; 

    console.log(event.data); 
} 

if ('addEventListener' in window){ 
    window.addEventListener('message', receiveMessage, false); 
} else if ('attachEvent' in window){ //IE 
    window.attachEvent('onmessage', receiveMessage); 

這些示例使用origin屬性限制消息發送到的位置,並檢查它來自哪裏。可以指定*以允許發送到任何域,並且在某些情況下您可能想要接受來自任何域的消息。但是,如果您這樣做,則需要考慮安全隱患並對收到的消息執行自己的檢查,以確保它包含您的期望。在這種情況下,iframe可以將它的高度發佈爲'*',因爲我們可能有多個父域。但是,檢查來自iFrame的傳入消息是個好主意。

function isMessageFromIFrame(event,iframe){ 
    var 
     origin = event.origin, 
     src  = iframe.src; 

    if ((''+origin !== 'null') && (origin !== src.substr(0,origin.length))) { 
     throw new Error(
      'Unexpect message received from: ' + origin + 
      ' for ' + iframe.id + '. Message was: ' + event.data 
     ); 
    } 

    return true; 
}