如a.com网站想通过JS获取b.com网站的数据。
1 在a.com网站添加一个空HTML页。名称为:http://a.com/null.html
2 在a.com网站需要获取数据页面(如:http://a.com/getDomainData.html)内容如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>跨域获取数据</title>
<script type="text/javascript">
function domainData(url, fn)
{
var isFirst = true;
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
var loadfn = function(){
if(isFirst){
iframe.contentWindow.location = 'http://a.com/null.html';
isFirst = false;
} else {
fn(iframe.contentWindow.name);
iframe.contentWindow.document.write('');
iframe.contentWindow.close();
document.body.removeChild(iframe);
iframe.src = '';
iframe = null;
}
};
iframe.src = url;
if(iframe.attachEvent){
iframe.attachEvent('onload', loadfn);
} else {
iframe.onload = loadfn;
}
document.body.appendChild(iframe);
}
</script>
</head>
<body>
</body>
<script type="text/javascript">
domainData('http://b.com/data.html', function(data){
alert(data);
});
</script>
</html>
3 在b.com中添加获取数据页面 如:http://b.com/data.html 内容需包含:
<script>
window.name = '需要跨域传递的数据';
</script>
4 访问 http://a.com/getDomainData.html 就可返回 http://b.com/data.html 中的window.name中的数据了。
需要注意的地方
null.html 是必须的。内容可为空。
iframe的onload事件绑定 必须这样写:
if(iframe.attachEvent){
iframe.attachEvent('onload', loadfn);
} else {
iframe.onload = loadfn;
}
调用domainData函数必须在body后面,或页面加载完后。
调用时会执行 http://b.com/data.html 页面的脚本。
原创话语:之前听说过window.name可以实现跨域,但是安全性值得商榷,不过既然是跨域,除了html5的postmessage之外貌似安全性都不高,
所以将其纳入跨域请求行列。