本文主要介紹通過設置 document.domain 來實現同一個父域下頁面間的通信,文中所使用到的軟件版本:Chrome 90.0.4430.212。
1、document.domain 設置描述
可以將頁面 document.domain 的值設置為其當前域或其當前域的父域。例如:在頁面 http://store.company.com/dir/other.html 上設置:
document.domain = "company.com";
端口號是由瀏覽器另行檢查的。任何對 document.domain 的賦值操作,包括 document.domain = document.domain 都會導致端口號被重寫為 null 。因此 company.com:8080 不能僅通過設置 document.domain = "company.com" 來與 company.com 通信。必須在他們雙方中都進行賦值,以確保端口號都為 null 。
注意:使用 document.domain 來允許子域安全訪問其父域時,您需要在父域和子域中設置 document.domain 為相同的值。這是必要的,即使這樣做只是將父域設置回其原始值。不這樣做可能會導致權限錯誤。
2、樣例
在 http://my.com:8080/a.html 中嵌入 iframe,地址為:http://abc.my.com:8080/b.html,然后在 a.html 中訪問 b.html 頁面中的 js 變量。
2.1、模擬域名訪問
在 C:\Windows\System32\drivers\etc\hosts 文件中增加:
127.0.0.1 my.com 127.0.0.1 abc.my.com
2.2、a.html
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>父頁面</title> <script type="text/javascript"> document.domain = "my.com"; function getOtherWindowValue() { let a = document.getElementById("frame").contentWindow.a; alert(a); } </script> </head> <body> <iframe src="http://abc.my.com:8080/b.html" frameborder="0" id="frame"></iframe> <button onclick="getOtherWindowValue()">test</button> </body> </html>
2.3、b.html
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>子頁面</title> <script type="text/javascript"> document.domain = "my.com"; var a = "hello"; </script> </head> <body> 子頁面 </body> </html>
2.4、部署訪問
把 a.html 和 b.html 放到 tomcat 的 webapps\ROOT 下,訪問地址為:http://my.com:8080/a.html。