zoukankan      html  css  js  c++  java
  • 跨域访问方法介绍(4)--使用 window.name 传值

    浏览器窗口有 window.name 属性。这个属性的最大特点是,无论是否同源,只要在同一个窗口里,前一个网页设置了这个属性,后一个网页可以读取它。这种方法的优点是,window.name 容量很大,可以放置非常长的字符串;缺点是必须监听子窗口 window.name 属性的变化,影响网页性能。本文主要介绍使用 window.name 来实现跨域数据传递,文中所使用到的软件版本:Chrome 90.0.4430.212。

    1、步骤说明

    在 a.html(http://localhost:8080/a.html) 页面打开 c.html(http://localhost:9090/c.html) 页面,c.html 页面设置 window.name 属性并跳转到 b.html(http://localhost:8080/a.html),此时在 a.html 页面就可以获取到 c.html 页面设置的 window.name 属性的值。

    2、a.html(http://localhost:8080/a.html)

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>window.name 测试</title>
    
    </head>
    <body>
        <button onclick="openChild()">打开子页面</button>
    </body>
    
    <script type="text/javascript">
        function openChild() {
            let childWindow = window.open("http://localhost:9090/c.html");
            
            //监听子窗口window.name的变化
            let interval = setInterval(function(){
                //子窗口window.name发生变化,停止定时任务
                if (childWindow.name) {
                    clearInterval(interval);
                    console.log(childWindow.name);
                    childWindow.close();
                }
            }, 2000);
        }
        
    </script>
    </html>

    3、b.html(http://localhost:8080/b.html)

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>代理页面</title>
    <script type="text/javascript">
        alert(window.name);    
    </script>
    </head>
    <body>
        操作成功。该页面即将自动关闭...
    </body>
    </html>

    4、c.html(http://localhost:9090/c.html)

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>数据</title>
    
    <script type="text/javascript">
        //模拟用户操作后,页面跳转
        setTimeout(function() {
            window.name = "你好";
            window.location.href = "http://localhost:8080/b.html";    
        }, 3000);
    </script>
    </head>
    <body>
       数据...
    </body>
    
    </html>

    5、测试

    把 a.html 和 b.html 放到 tomcat (端口:8080) 的 webappsROOT 下,c.html 放到另一个 tomcat (端口:9090) 的 webappsROOT 下。

  • 相关阅读:
    VS2010中经常使用的快捷键
    IE无法打开internet网站已终止操作的解决的方法
    Spring3.0 AOP 具体解释
    Java 反射机制[Method反射]
    软件測试自学指南---从入门到精通
    Java中Map的使用
    tracert路由跟踪命令分析判断
    C++ Primer 学习笔记_32_STL实践与分析(6) --再谈string类型(下)
    ORACLE触发器具体解释
    Androidclient推断server是否开启 HttpHostException解决方式
  • 原文地址:https://www.cnblogs.com/wuyongyin/p/14857702.html
Copyright © 2011-2022 走看看