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

不同源页面

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

第一个页面: 发送页面 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 2022-03-26 15:44  GameCat  阅读(127)  评论(0编辑  收藏  举报

导航