zoukankan      html  css  js  c++  java
  • 跨域访问方法介绍(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:WindowsSystem32driversetchosts 文件中增加:

    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 的 webappsROOT 下,访问地址为:http://my.com:8080/a.html。

  • 相关阅读:
    【转】 IntelliJ IDEA 详细图解最常用的配置 ,适合刚刚用的新人
    安装IntelliJ IDEA默认C盘文件过大怎么办
    [linux]netstat命令详解-显示linux中各种网络相关信息
    [linux]free命令详解-显示内存的使用情况
    用什么工具能找出性能瓶颈?
    [linux]iostat命令详解-监视系统输入输出设备和CPU的使用情况
    [linux]vmstat命令详解-显示虚拟内存状态
    好文章列表
    BigDecimal.setScale 处理java小数点
    Mybatis通用分页
  • 原文地址:https://www.cnblogs.com/wuyongyin/p/14835871.html
Copyright © 2011-2022 走看看