iframe使用postMessage发送消息

37 阅读1分钟

主项目


<html>
  <head>
    <title>主项目</title>
  </head>

  <body>
    <iframe id="iframe" src="http://127.0.0.1:5501/index.html"></iframe>
    <button onclick="getData()">iframe数据通信</button>
    <button onclick="getToken()">获取子应用Token</button>
  </body>

  <script>
    function getData() {
        var iframe = document.getElementById("iframe");
        iframe.contentWindow.postMessage("我是主项目", "*");
    }

    function getToken() {
        var iframe = document.getElementById("iframe");
        console.log(iframe.contentWindow.getToken());
    }

    window.addEventListener('message', function(e) {
            console.log(e);
            // 获取父项目发送的数据
            var data = e.data;
            // 获取父项目发送的数据类型
            var type = e.type;
            alert(data);
        })
  </script>
</html>

子项目

<html>
    <head>
        <title>子项目</title>
    </head>

    <body>
        <button onclick="setToken()">子项目iframe数据通信</button>
    </body>
    
    <script>
        // 接收父项目传输的消息
        window.addEventListener('message', function(e) {
            console.log(e);
            // 获取父项目发送的数据
            var data = e.data;
            // 获取父项目发送的数据类型
            var type = e.type;
            // 获取父项目发送的数据内容

            // 根据数据类型做不同的处理
            switch(type) {
                case 'message':
                    alert('父项目发送的数据内容是:' + data);
                    window.parent.postMessage(window.localStorage.getItem('token'), '*');
            }
        })

        function setToken() {
            // 向父项目发送数据
           window.localStorage.setItem('token', '123456789');
        }

       
        
    </script>
</html>