在 http://www.cnblogs.com/zhuzhenwei918/p/6759459.html 这篇文章中,我提到了几种跨域的方式,这里主要讲解使用window.name实现跨域。
跨域就是说必须同协议、域名、端口号,我们才能获取其内容,对其进行访问。
window.name这个属性不是一个简单的全局属性 --- 只要在一个window下,无论url怎么变化,只要设置好了window.name,那么后续就一直都不会改变,同理,在iframe中,即使url在变化,iframe中的window.name也是一个固定的值,利用这个,我们就可以实现跨域了。
下面是localhost:8088/test2.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test2</title>
</head>
<body>
<h2>test2页面</h2>
<script>
var person = {
name: 'wayne zhu',
age: 22,
school: 'xjtu'
}
window.name = JSON.stringify(person)
</script>
</body>
</html>

即我们希望吧test2.html中的数据传递出去,到localhost:8081/test1.html中去。
下面是localhost:8081/test1.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test1</title>
</head>
<body>
<h2>test1页面</h2>
<iframe src="http://localhost:8088/test2.html" frameborder="1"></iframe>
<script>
var ifr = document.querySelector('iframe')
ifr.style.display = 'none'
var flag = 0;
ifr.onload = function () {
if (flag == 1) {
console.log('跨域获取数据', ifr.contentWindow.name);
ifr.contentWindow.close();
} else if (flag == 0) {
flag = 1;
ifr.contentWindow.location = 'http://localhost:8081/proxy.html';
}
}
</script>
</body>
</html>

这里的意图很明确,就是使用iframe将test2.html加载过来,因为只是为了实现跨域,所以将之隐藏,但是,这时已经完成了最重要的一步,就是将iframe中window.name已经成功设置,但是现在还获取不了,因为是跨域的,所以,我们可以把src设置为当前域的proxy.html。
另外,这里之所以要设置flag,是因为每当改变location的时候,就会重新来一次onload,所以我们希望获取到数据之后,就直接close(),故采用此种方法。
这个proxy.html内容如下:
按 Ctrl+C 复制代码
按 Ctrl+C 复制代码
是的,什么都没有,当然,我们也可以把src就替换成test1.html,但是这样的坏处很明显,就是需要把test1.html中的数据加载一遍,这不是我们所希望的。
OK! 这样,就成功完成了跨域!
代码: https://github.com/zzw918/cross-origin
如我们希望localhost:8081/test1.html可以访问到localhost:8088/test2.html中的数据,正常来说,由于跨域,这一定是不可能的,一般的实现思路可以是这样的。
本文介绍了一种利用window.name属性实现跨域数据传递的方法,通过iframe加载不同源的页面并利用window.name的持久特性,实现在不同域间的数据交换。
453

被折叠的 条评论
为什么被折叠?



