2014-09-29 107 views
1

如何獲得iframe中的iframe屬性的JavaScript代碼獲取iframe中的iframe JavaScript和跨域

<div> 
<iframe src="http://192.168.0.108:8092/" 
      name="otherDomain" 
      width="100%" 
      height="600px" 
      style="border: 0;" 
      data-auth-token="xyz" 
      data-auth-key="abc" 
     > 
</div> 

我與

console.log(window.frameElement.getAttribute('data-auth-token')) 

試圖屬性如果iframe網址和瀏覽器的用戶是相同的,我能夠獲取iframe屬性。如果網址不同,我會收到以下錯誤消息。

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

是否有可能在JavaScript中獲得跨域iframe屬性。

回答

2

不幸的是,您不可能使用引用其他域的iframe。瀏覽器會自動阻止所有嘗試從另一個域訪問幀的腳本。如果這樣的事情是可能的,那麼這將是一個巨大的安全缺陷。

在你的情況,你可以將iframe屬性設置srclocalhost:8092,所以你必須以相同的位置(和相同的域名)的iframe,你就可以訪問其數據。

+0

感謝您的解釋@Marco Bonelli。我想錯了。 – Prasanna 2014-09-29 08:50:29