關於跨域的N種方法實踐之iframe+domain

1、原理html

  一、主域相同,子域不一樣,能夠設置document.domain來解決跨域。gulp

  二、在http://www.example.com/a.html和http://sub.example.com/b.html兩個文件中都加上document.domain = "example.com";跨域

  三、經過a.html文件建立一個iframe,去控制iframe的window,從而進行交互。瀏覽器

2、測試方法服務器

  一、經過gulp啓用兩個本地服務器,並在hosts文件映射域名(主域名相同,子域名不一樣)如:app

    127.0.0.1     www.jiangqi.cndom

    127.0.0.1     top.jiangqi.cn測試

  二、服務器A的代碼spa

<!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() {
//=========================================1、分割線(跨域實踐)================================================================================
    let ifrWin1 = ifrObj.contentWindow;
    alert(ifrWin1.data)
    //一、直接得到iframe的window對象以後,獲取iframe傳過來的data
//=========================================2、分割線(iframe對象的contentWindow屬性)===========================================================      
      //一、經過iframe對象的contentWindow(非標準屬性;只讀;大多瀏覽器都支持),返回指定的iframe的窗口對象
    let ifrWin2 = ifrObj.contentWindow;
    //二、給指定iframe對象的window對象傳遞參數(父子頁面傳參)
    ifrWin2.username = '張三'
    //三、直接獲取iframe頁面內的元素並操做dom元素
    var obj=  ifrWin2.document.getElementsByTagName('p')[0].innerText ="22";
    //四、在子iframe裏能夠經過window.parent或者window.top訪問父級頁面的dom
//=========================================3、分割線(iframe對象的contentDocument屬性)=========================================================
    //一、直接獲取iframe頁面內的元素並操做dom元素。
    let ifrDoc = ifrObj.contentDocument;
    ifrDoc.getElementsByTagName('p')[0].innerText ="33"
  }
</script>
</body>
</html>

  三、服務器B的代碼code

<!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>

3、參考

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

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

相關文章
相關標籤/搜索