JS 使用window.name跨域实践

特将具体实现方法记录如下:

如a.com网站想通过JS获取b.com网站的数据。

1.在a.com网站添加一个空HTML页。名称为:http://a.com/null.html

2.在a.com网站需要获取数据页面(如:http://a.com/getDomainData.html )内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!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 内容需包含:

1
2
3
<script>
  window.name = '需要跨域传递的数据';
</script>

4.访问 http://a.com/getDomainData.html 就可返回 http://b.com/data.html 中的window.name中的数据了。

需要注意的地方

null.html 是必须的。内容可为空。

iframe的onload事件绑定 必须这样写:

1
2
3
4
5
if(iframe.attachEvent){
iframe.attachEvent('onload', loadfn);
} else {
iframe.onload = loadfn;
}

调用domainData函数必须在body后面,或页面加载完后。

调用时会执行 http://b.com/data.html 页面的脚本。