一、原理
1、iframe內聯框架的src屬性跨域加載資源的能力
2、window.name 值在不同的頁面(甚至不同域名)加載后依舊存在(如果沒修改則值不會變化),並且可以支持非常長的 name 值(2MB)或者說 window.name屬性值在文檔刷新后依舊存在的能力
二、總體框架及代碼
1、A域中的獲取數據頁:index.html
<!DOCTYPE html> <html> <head> <title>A域(window.name+iframe跨域解決方案)</title> </head> <body> </body> <script type="text/javascript"> var ifr = document.createElement("iframe"); ifr.style.display="none"; ifr.src = "http://top.jiangqi.cn:8081/index2.html"; document.getElementsByTagName("head")[0].appendChild(ifr); var flag = 0; ifr.onload = function(){ if(flag == 0){ flag = 1; ifr.contentWindow.location = 'http://www.jiangqi.cn/windowName/proxy.html'; }else{ //獲取數據 console.log(JSON.parse(ifr.contentWindow.name)) //釋放內存,銷毀iframe ifr.contentWindow.close(); document.getElementsByTagName("head")[0].removeChild(ifr); } } </script> </html>
2、A域中的代理頁(空文檔,只起到window.name轉同域作用):proxy.html
<!DOCTYPE html> <html> <head> <title></title> </head> <body> </body> </html>
3、B域中的數據源頁:index.html
<!DOCTYPE html> <html> <head> <title>window.name+iframe跨域解決方案)</title> </head> <body> </body> <script type="text/javascript"> var person = { name:"蔣*", age:"26", education:"大學本科" } window.name = JSON.stringify(person) </script> </html>
三、參考
1、https://www.tuicool.com/articles/viMFbqV
2、https://segmentfault.com/a/1190000011145364