百木园-与人分享,
就是让自己快乐。

跨域访问方法介绍(3)--使用片段识别符传值

片段标识符(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)

<!DOCTYPE html>
<html>
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<title>片段识别符 测试</title>

</head>
<body>
<iframe src=\"http://localhost:9090/b.html\" id=\"frame\"></iframe>

父页面
<button onclick=\"sendMessage()\">向子页面传数据</button>
</body>

<script type=\"text/javascript\">
function sendMessage() {
let src
= document.getElementById(\'frame\').src;
document.getElementById(
\'frame\').src = src + \"#hello\";
}

window.onhashchange = function() {
alert(window.location.hash);
}

</script>
</html>

来源:https://www.cnblogs.com/wuyongyin/p/14861869.html
图文来源于网络,如有侵权请联系删除。

未经允许不得转载:百木园 » 跨域访问方法介绍(3)--使用片段识别符传值

相关推荐

  • 暂无文章