window.name实现跨域

   在 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内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>proxy</title>
</head>
<body>
  <p>这是proxy页面</p>
</body>
</html>

  是的,什么都没有,当然,我们也可以把src就替换成test1.html,但是这样的坏处很明显,就是需要把test1.html中的数据加载一遍,这不是我们所希望的。

  

  

  OK! 这样,就成功完成了跨域! 

  代码: https://github.com/zzw918/cross-origin

  

  

  

  

 

 

 

 

 

 

   

  如我们希望localhost:8081/test1.html可以访问到localhost:8088/test2.html中的数据,正常来说,由于跨域,这一定是不可能的,一般的实现思路可以是这样的。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值