片段識別符號(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>
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"> window.onhashchange = function() { alert(window.location.hash); parent.location.href = "http://localhost:8080/a.html#haha"; } </script> </head> <body> 子頁面 </body> </html>
4、測驗
把 a.html 放到 tomcat (埠:8080) 的 webapps\ROOT 下,b.html 放到另一個 tomcat (埠:9090) 的 webapps\ROOT 下,


轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/288155.html
標籤:HTML5
