末到派對,但我已經設法破解它:它不檢測iFrame是否正確加載,但它會檢測服務器是否可以訪問。爲了您的使用,您可以翻轉邏輯,並在服務器負載成功後隱藏某些內容。首先,我想做一個AJAX調用來測試網站a)是否存在以及b)是否允許跨源調用,但最初它並不適用於我,因爲我使用過jQuery。它完美,如果你做一個XMLHttpRequest:
var url = http://url_to_test.com/
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status != 200) {
console.log("iframe failed to load");
}
};
xhttp.open("GET", url, true);
xhttp.send();
編輯:
所以這種方法效果好,但它有很多的假陰性(拿起了很多的東西,會在iframe顯示)由於交叉來源malarky。我解決這個問題的方式是在服務器上執行CURL/Web請求,然後檢查a)網站是否存在,以及b)如果標頭已設置x-frame-options
。
如果您運行自己的網絡服務器,這不是問題,因爲您可以自己創建API調用。
我在node.js中實現:
app.get('/iframetest',function(req,res){ //Call using /iframetest?url=url - needs to be stripped of http:// or https://
var url = req.query.url;
var request = require('https').request({host: url}, function(response){ //This does an https request - require('http') if you want to do a http request
var headers = response.headers;
if (typeof headers["x-frame-options"] != 'undefined') {
res.send(false); //Headers don't allow iframe
} else {
res.send(true); //Headers don't disallow iframe
}
});
request.on('error',function(e){
res.send(false); //website unavailable
});
request.end();
});
負載事件將觸發即使在IE9的錯誤。 – jcoffland 2013-01-22 01:36:40