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

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

一、步骤说明

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

二、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>

三、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">
    window.onhashchange = function() {
        alert(window.location.hash);
        parent.location.href = "http://localhost:8080/a.html#haha";
    }
</script>
</head>
<body>
   子页面
</body>

</html>

四、测试

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

相关文章
相关标签/搜索