跨域-降域

来源:互联网 发布:ncbi sra数据库 编辑:程序博客网 时间:2024/06/14 06:29

页面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.htmldocument.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.htmldocument.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 0
原创粉丝点击