关于跨域的N种方法实践之iframe+domain

一、原理

  1、主域相同,子域不同,可以设置document.domain来解决跨域。

  2、在http://www.example.com/a.html和http://sub.example.com/b.html两个文件中都加上document.domain = "example.com";

  3、通过a.html文件创建一个iframe,去控制iframe的window,从而进行交互。

二、测试方法

  1、通过gulp启用两个本地服务器,并在hosts文件映射域名(主域名相同,子域名不同)如:

    127.0.0.1     www.jiangqi.cn

    127.0.0.1     top.jiangqi.cn

  2、服务器A的代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>我是A</title>
</head>
    <p id="app2">我是a</p>
<body>
<script>

  document.domain = 'jiangqi.cn';
  let ifrObj = document.createElement('iframe');
  ifrObj.src = 'http://top.jiangqi.cn:8081/';
  //ifrObj.style.display = 'none';
  document.body.appendChild(ifrObj);
  ifrObj.onload = function() {
//=========================================一、分割线(跨域实践)================================================================================
    let ifrWin1 = ifrObj.contentWindow;
    alert(ifrWin1.data)
    //1、直接获得iframe的window对象之后,获取iframe传过来的data
//=========================================二、分割线(iframe对象的contentWindow属性)===========================================================      
      //1、通过iframe对象的contentWindow(非标准属性;只读;大多浏览器都支持),返回指定的iframe的窗口对象
    let ifrWin2 = ifrObj.contentWindow;
    //2、给指定iframe对象的window对象传递参数(父子页面传参)
    ifrWin2.username = '张三'
    //3、直接获取iframe页面内的元素并操作dom元素
    var obj=  ifrWin2.document.getElementsByTagName('p')[0].innerText ="22";
    //4、在子iframe里可以通过window.parent或者window.top访问父级页面的dom
//=========================================三、分割线(iframe对象的contentDocument属性)=========================================================
    //1、直接获取iframe页面内的元素并操作dom元素。
    let ifrDoc = ifrObj.contentDocument;
    ifrDoc.getElementsByTagName('p')[0].innerText ="33"
  }
</script>
</body>
</html>

  3、服务器B的代码

<!DOCTYPE html>
<html>
<head>
    <title>我是B域</title>
</head>
<body>
    <p id="app">b</p>
<script>
    document.domain = 'jiangqi.cn';
    window.data = '传送的数据:1111';

    var obj = parent.document.getElementsByTagName('p')[0]
    obj.innerText = "我把A改成了B"
</script>
</body>
</html>

三、参考

  1、https://www.cnblogs.com/camille666/p/cross_domain_document_domain.html

  2、https://www.cnblogs.com/goloving/p/7828070.html

原文地址:https://www.cnblogs.com/helloNico/p/10614039.html