浏览器内多个标签页之间的如何通信
不同源页面
这里造成不同源的方式是: 不同端口
第一个页面: 发送页面 send.html
<!DOCTYPE html>
<html>
<head>
<title>send</title>
</head>
<body>
<iframe id="testTwo" src="http://127.0.0.1:8080/">
</iframe>
<button id="test">按钮1</button>
<script>
var button = document.getElementById("test")
var frame = document.getElementById("testTwo")
var iframe = null
button.addEventListener("click", function () {
frame.contentWindow.postMessage("我向你发送消息", "http://127.0.0.1:8080/");
})
</script>
</body>
</html>
发送页面有一个iframe, 点击按钮是利用 iframe.contentWindow.postMessage 向 http://127.0.0.1:8080/ 首页发送消息
第二个页面: 接收页面 index.html
<!DOCTYPE html>
<html>
<head>
<title>接收</title>
</head>
<body>
<script>
window.addEventListener("message", function (res) {
console.log(res.data)
console.log(res.origin)
})
</script>
</body>
</html>
接收页面给window添加事件监听, 监听message, 可以发现最后接收信息
结果
点击 按钮, 在控制台查看输出
同源页面
同源页面主要用localStorage 来传递
第一个页面
<!DOCTYPE html>
<html>
<head>
<title>one</title>
</head>
<body>
<button id="btn">按钮</button>
<script>
var btn = document.getElementById("btn")
btn.addEventListener("click", function(){
localStorage.setItem("name", "yangjing")
console.log('123')
})
</script>
</body>
</html>
第二个页面
<!DOCTYPE html>
<html>
<head>
<title>two</title>
</head>
<body>
<button id="btn">按钮</button>
<script>
var btn = document.getElementById("btn")
btn.addEventListener("click", function () {
console.log( localStorage.getItem("name"))
})
</script>
</body>
</html>
这是我的签名
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库