经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » HTML/CSS » HTML5 » 查看文章
跨域访问方法介绍(4)--使用 window.name 传值
来源:cnblogs  作者:咏吟  时间:2021/6/21 10:05:48  对本文有异议

浏览器窗口有 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)

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>window.name 测试</title>
  6.  
  7. </head>
  8. <body>
  9. <button onclick="openChild()">打开子页面</button>
  10. </body>
  11.  
  12. <script type="text/javascript">
  13. function openChild() {
  14. let childWindow = window.open("http://localhost:9090/c.html");
  15. //监听子窗口window.name的变化
  16. let interval = setInterval(function(){
  17. //子窗口window.name发生变化,停止定时任务
  18. if (childWindow.name) {
  19. clearInterval(interval);
  20. console.log(childWindow.name);
  21. childWindow.close();
  22. }
  23. }, 2000);
  24. }
  25. </script>
  26. </html>

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

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

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

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>数据</title>
  6.  
  7. <script type="text/javascript">
  8. //模拟用户操作后,页面跳转
  9. setTimeout(function() {
  10. window.name = "你好";
  11. window.location.href = "http://localhost:8080/b.html";
  12. }, 3000);
  13. </script>
  14. </head>
  15. <body>
  16. 数据...
  17. </body>
  18.  
  19. </html>

5、测试

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

原文链接:http://www.cnblogs.com/wuyongyin/p/14857702.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号