跨域访问方法介绍(2)--设置 document.domain

本文主要介绍通过设置 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。

 

posted @ 2021-06-14 17:35  且行且码  阅读(1467)  评论(0编辑  收藏  举报