• 跨域访问方法介绍(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 下。

  • 相关阅读:
    关于Web应用开发流程的总结
    package.json的所有配置项及其用法,你都熟悉么
    curl 命令行工具的使用及命令参数说明
    pytest插件探索——hook开发
    浅探前端图片优化
    使用Flask构建一个Web应用
    原生的js实现jsonp的跨域封装
    CSS定位之BFC背后的神奇原理
    webview错误
    Android 中的webview
  • 原文地址:https://www.cnblogs.com/wuyongyin/p/14857702.html
Copyright © 2020-2023  润新知