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

片段标识符(fragment identifier)指的是,URL 中 # 号后面的部分,比如 http://example.com/x.html#fragment 的 #fragment。如果只是改变片段标识符,页面不会重新刷新。父窗口可以把信息,写入子窗口的片段标识符。子窗口通过监听 hashchange 事件得到通知;同样的,子窗口也可以改变父窗口的片段标识符。本文主要介绍使用片段标识符来实现跨域数据传递,文中所使用到的软件版本:Chrome 90.0.4430.212。

1、步骤说明

在 a.html(http://localhost:8080/a.html) 页面嵌入 b.html(http://localhost:9090/b.html) 页面,然后 a.html 改变 b.html 的片段标识符,b.html 接受到消息后改变父页面的片段标识符。

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>片段识别符 测试</title>
  6.  
  7. </head>
  8. <body>
  9. <iframe src="http://localhost:9090/b.html" id="frame"></iframe>
  10. 父页面
  11. <button onclick="sendMessage()">向子页面传数据</button>
  12. </body>
  13.  
  14. <script type="text/javascript">
  15. function sendMessage() {
  16. let src = document.getElementById('frame').src;
  17. document.getElementById('frame').src = src + "#hello";
  18. }
  19. window.onhashchange = function() {
  20. alert(window.location.hash);
  21. }
  22. </script>
  23. </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.  
  7. <script type="text/javascript">
  8. window.onhashchange = function() {
  9. alert(window.location.hash);
  10. parent.location.href = "http://localhost:8080/a.html#haha";
  11. }
  12. </script>
  13. </head>
  14. <body>
  15. 子页面
  16. </body>
  17.  
  18. </html>

4、测试

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

 

原文链接:http://www.cnblogs.com/wuyongyin/p/14861869.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号