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