2012-04-28 23 views
6

在我的本地,我使用下面的JavaScript來創建一個iframesrc,並將其添加到文檔:內容動態生成的iframe的是空

$('#preview').html('<iframe src="http://google.com/"></iframe>'); 

iframe的表演而不是內容。在螢火蟲,它只是:

<iframe src="http://google.com/"> 
    <html> 
     <head></head> 
     <body></body> 
    </html> 
</iframe> 

當我在控制檯上執行$('iframe').attr('src','http://google.com/');,瀏覽器加載(說「等待google.com ...」),然後似乎刷新iframe的內容。但是,它又是空的。

但是,如果將其設置爲本地頁面,則會加載內容。

這是因爲相同的產地政策?我不知道這件事。我做了一些谷歌搜索,我很困惑,因爲有些網站說,包含一個不屬於你自己的域的src的iframe是可以的,有人說這是不可能的。

順便說一句,因爲我仍然在本地主機上測試,如果我上傳到服務器的某個地方,這個工作嗎? (但是iframe的src仍然會在不同的域中)

幫助?

回答

12

如果你檢查瀏覽器的錯誤控制檯,你會看到這樣一條消息:

拒絕了,因爲顯示的X型框架,選項禁止顯示文件。

因此,這不是您的錯誤,而是Google的故意行爲。

X-Frame-Options有兩個選項:

  • deny - 框架內沒有渲染和
  • sameorigin - 沒有渲染,如果原產地不一致

參考文獻:

+0

非常感謝。第三個鏈接(SO)很有幫助,因爲我試圖將google地圖加載到iframe中。 – Obay 2012-04-28 19:22:20

+0

非常歡迎,我很高興得到了幫助=) – 2012-04-28 19:23:40

4

是的代碼由於相同的原產地政策被禁止。閱讀here

假設你擁有那麼域http://www.example.com你大概可以有以下結果,當您通過I幀調用網頁:

Compared URL        Outcome Reason 
--------------------------------------------------------------------------------------------- 
http://www.example.com/dir/page.html  Success Same protocol and host 
http://www.example.com/dir2/other.html  Success Same protocol and host 
http://www.example.com:81/dir2/other.html Failure Same protocol and host but different port 
https://www.example.com/dir2/other.html Failure Different protocol 
http://en.example.com/dir2/other.html  Failure Different host 
http://example.com/dir2/other.html   Failure Different host (exact match required) 
http://v2.www.example.com/dir2/other.html Failure Different host (exact match required) 

現在,你在呼喚google.com,這是在一個跨域問題您。爲了解決這個問題,JSONP可以幫助你。它使用<script>的開放腳本策略,從跨域中檢索JSON。