前端多页面通信

    科技2025-11-01  18

    原文地址: https://juejin.im/post/6844903811232825357

    以下仅供自己实践时做的笔记

    当两个页面同源时:

    使用 BroadcastChannel 先使用express 服务器启动 web 服务器。然后浏览器中打开两个自己 express 的页面。 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> 这里是服务端渲染的文件 <div onclick="clickButton()">点击发送消息</div> </body> <script> let bc = new BroadcastChannel("daimian"); bc.onmessage = function (e) { console.log("这里是接收到的消息:", e.data); }; function clickButton() { console.log("这里点击了按钮"); bc.postMessage("这里是广播发送的消息"); } </script> </html>

    一个页面发送

    另一个页面接收:

    监听 locaStorage

    使用 eventListener 监听 storage

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> 这里是服务端渲染的文件 <div onclick="clickButton()">点击发送消息</div> </body> <script> window.addEventListener("storage", (e) => { console.log("这里storage进行了变化", e); }); let num = 0; function clickButton() { localStorage.setItem("nice", num++); } </script> </html>

    使用 indexDB 然后进行轮训使用 serviceWorker 自己制作一个信息中转站。

    不同源时

    使用 postMessage 和 iframe 进行跨域传输数据。 需要注意的是: 不能把 targetWindow.postMessage 直接写在script标签内,因为 iframe 标签加载很慢,所以会报错 因此,要放在事件里面,通过事件触发。这样等到 iframe 加载完成后可以获得 iframe 的 window ,然后发送消息。

    或者可以用setTimeout

    parent 页面,挂载载 http://localhost:3000 上

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>iframe父级页面</title> <style> * { padding: 0; margin: 0; } </style> </head> <body> <h2>我是父级页面</h2> <iframe src="http://localhost:3001" id="myframe"></iframe> <script> setTimeout(() => { var myframe = document.getElementById("myframe"); myframe.contentWindow.postMessage("hello", "http://localhost:3001"); }, 1000); </script> </body> </html>

    child子页面,挂载在 http://localhost:3001 上

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>iframe子页面</title> </head> <body> <h2>我是内嵌的子页面</h2> <script> window.addEventListener("message", function (e) { console.log("这里是父页面传的值:", e.data); }); </script> </body> </html>

    Processed: 0.009, SQL: 8