下面是参考文献[1]的一个实践验证,测试环境略有修改,记录如下:
测试场景:从网站A中的网页去获取网站B中网页的数据
下面以news.sina.com.cn和news.163.com这两个站点为例,将如下网页都放到Nginx服务器根目录下面的子目录taoyx-test下面:
PageA.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>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<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://news.sina.com.cn/taoyx-test/PageNull.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://news.163.com/taoyx-test/PageB.html', function(data){
alert(data);
});
</script>
</html>
PageNull.html内容如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Windows.name变量测试</title>
<link rel="shortcut icon" href="http://t10.baidu.com/it/u=4094539827,178906815&fm=58" />
</head>
<body>
</body>
</html>
PageB.html内容如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Windows.name变量测试</title>
<link rel="shortcut icon" href="http://t10.baidu.com/it/u=4094539827,178906815&fm=58" />
</head>
<body>
<script>
window.name = '需要跨域传递的数据: cross-domain data,======= 雪峰流云!========';
</script>
</body>
</html>
为了创造两个域名的环境,可以在hosts文件中添加如下域名:
10.10.110.149 news.sina.com.cn
10.10.110.149 news.163.com
在chrome中打开如下链接,
得到如下效果图
注意事项:
1.PageNull.html 是必须的。内容可为空。
2.iframe的onload事件绑定 必须这样写:
if(iframe.attachEvent){
iframe.attachEvent('onload', loadfn);
} else {
iframe.onload = loadfn;
}
3.调用domainData函数必须在body后面,或页面加载完后。调用时会执行 http://news.163.com/taoyx-test/PageB.html 页面的脚本。
参考文献
[1].http://www.cnblogs.com/zjfree/archive/2011/02/24/1963591.html