2014-04-29 85 views
2

對於以下iframe,Safari永遠不會調用onload函數,並且不會在iframe中顯示任何內容。我測試過的所有其他瀏覽器都會調用onload並顯示默認錯誤網頁。當src無效時,Safari不會調用iframe onload

<html> 
<body> 
<iframe src="http://www.asdkjhjhkjhkjhjhjhfhkjhsdflkjahdsjfhasf.com" 
     onload="alert('iframe loaded');"> 
</iframe> 
</body> 
</html> 

爲什麼會發生這種情況?如果這個問題沒有解決方案,那麼我需要找到一種方法來檢測iframe是否無法加載。

+0

是否調用了錯誤? – alex

+0

@alex你錯誤的意思是什麼?我知道onerror屬性,但它不適用於我知道的任何當前瀏覽器上的iframe – functionptr

回答

2

我只是在前一天偶然發現了this post,並解決了Safari中缺少的load event的解決方法。該帖子是從2011年,但似乎仍然有效。

提出有Safari的解決方案是,以檢查readyState事件的iframedocument像這樣:

<iframe id="ifra" src="http://www.asdkjhjhkjhkjhjhjhfhkjhsdflkjahdsjfhasf.com" 
     onload="alert('iframe loaded');"> 
</iframe> 
<script> 
    var iframe = document.getElementById('ifra'), 
     doc = iframe.contentDocument || iframe.contentWindow; 
    if (doc.document) doc = doc.document; 
    var _timer = setInterval(function() { 
     if (doc.readyState == 'complete') { 
      clearInterval(_timer); 
      alert('iframe ready'); 
     } 
    }, 1000); 
</script> 

按照Mozilla's documentation on contentDocument,你不會需要包括與contentWindow時的解決方法只在Safari中運行這個腳本,但是我保留在這裏以防萬一你想跨瀏覽器使用它。