博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

JS 使用window.name跨域实践

Posted on 2011-02-24 11:34  PHP-张工  阅读(11646)  评论(6编辑  收藏  举报

看了园友的 window.name实现的跨域数据传输

自己实践了一下,真的很好用。

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

如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 页面的脚本。