跨域-降域

页面a:

<html>
<style>
  .ct{
    width: 910px;
    margin: auto;
  }
  .main{
    float: left;
    width: 450px;
    height: 300px;
    border: 1px solid #ccc;
  }
  .main input{
    margin: 20px;
    width: 200px;
  }
  .iframe{
    float: right;
  }

  iframe{
    width: 450px;
    height: 300px;
    border: 1px dashed #ccc;
  }
</style>

<div class="ct">
  <h1>使用降域实现跨域</h1>
  <div class="main">
    <input type="text" placeholder="http://a.wuxiaozhou.com/a.html">
  </div>

  <iframe src="http://b.wuxiaozhou.com/b.html" frameborder="0" ></iframe>

</div>


<script>
//URL: http://a.wuxiaozhou.com/a.html

document.querySelector('.main input').addEventListener('input', function(){
  console.log(this.value);
  window.frames[0].document.querySelector('input').value = this.value;
})


document.domain = "wuxiaozhou.com"



</script>
</html>

页面b:

<html>
<style>
    html,body{
        margin: 0;
    }
    input{
        margin: 20px;
        width: 200px;
    }
</style>

    <input id="input" type="text"  placeholder="http://b.wuxiaozhou.com/b.html">
<script>

// URL: http://b.wuxiaozhou.com/b.html

document.querySelector('#input').addEventListener('input', function(){
    window.parent.document.querySelector('input').value = this.value;
})

document.domain = 'wuxiaozhou.com';

</script>
</html>

域名为http://b.wuxiaozhou.com/b的网页以iframe的形式嵌在域名为http://a.wuxiaozhou.com/a的网页中,它们来自不同的域名,正常情况下不能进行跨域访问。

但是当我们为两个页面都加上这样一句代码:

document.domain = 'wuxiaozhou.com';

这时候这两个页面就位于同一个域名下面了,就可以在页面a中对页面b进行操作了,两个页面可以互相访问。

但是这个方法有个限制,相信你也发现了,就是两个域名要有相同对的部分才可以,比如这个例子中的就都含有wuxiaozhou.com这一部分。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值