浏览器内多个标签页之间的如何通信

不同源页面

这里造成不同源的方式是: 不同端口

第一个页面: 发送页面 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>

posted on   GameCat  阅读(136)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

统计

点击右上角即可分享
微信分享提示