好的,我理解使用 iframe 加载要避免的东西的诱惑same origin policy
,但我想提请您注意其他事情:CORS
考虑这种情况,网站 alice.com 有一些网站 bob.com 想要访问的数据。通过支持 CORS 请求,alice.com 可以添加一些特殊的响应标头,允许 bob.com 访问数据。
端到端示例:
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Helper method to parse the title tag from the response.
function getTitle(text) {
return text.match('<title>(.*)?</title>')[1];
}
// Make the actual CORS request.
function makeCorsRequest() {
// All HTML5 Rocks properties support CORS.
var url = 'http://updates.html5rocks.com';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
运行示例并在浏览器的调试器中观察网络请求,以查看发出的实际请求。
此外,您可以访问我提到的网站,以全面了解该方法的工作原理。