VUE中iframe结合window.postMessage实现跨域通信

兼容
IE11+ && other
1
主要使用方法
window.otherWindow.postMessage(data,orign)
1
中文介绍文档 https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage

参数说明:
data: 发送的数据。接受范围:字符串、数字、对象、数组(不能包含当前页可执行方法,也就是不能传递Function)
orign:接收消息的域名,比如页面存在多个iframe,可以通过设置这个值,指定哪个iframe接收消息,如果所有页面都接收,可以填写 “*”。

测试环境
创建两个 html 分别为A.html、B.html,通过localhost和127.0.0.1进行跨域测试。
A.html 使用 http://127.0.0.1/xxx/A.html 访问
B.html 使用 http:// localhost/xxx/B.html 访问

具体代码

A.html


<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">

    <title>页面A</title>
</head>
<body>
    

    <div>
        <div>这是A页面</div>
        <button onclick="senMsg()">发送数据给子页面</button>

        <div id="msgView" style="white-space: pre-line; background: #009; color:#fff;"></div>
    </div>

    <iframe id="myFrame" style="width:800px; height:300px; border:none; margin: 20px 0; " src="http://localhost/kuayu/B.html"></iframe>


    <script>
        /*
        *  父页向子页面发送数据
        */
        var senMsg = function(){
            var myFrame = document.getElementById('myFrame');
            myFrame.contentWindow.postMessage({
                title: "标题",
                msg: 'Hello B Page!',
                date: Date.now()
            },"http://localhost")
        }

        // 监听 子页面传递的消息
        window.addEventListener('message',function(event){
            var txt = "这是A页面,收到子页面发送的数据:\n"+event.data;
            console.log('----------- '+txt);
            document.getElementById('msgView').innerHTML = txt;
        }, false);
    </script>

</body>
</html>

B.html


<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">

    <title>页面B</title>
</head>
<body style="background: #efefef;">

    <div>
        <div>这是B页面</div>
        <p>
            <button onclick="senMsgToParent()">发送数据给父页面</button>
        </p>
    </div>

    <div style="border:1px solid #090; padding:10px;">
        <p><h3>父页面传来的消息</h1></p>
        <p id="msgView"></p>
    </div>

    <script>
        window.addEventListener('message',function(event){
            document.getElementById('msgView').innerHTML =  JSON.stringify(event.data);
        }, false);

        // 发送数据给父页面
        var senMsgToParent = function(){
            window.parent.postMessage("Hello I'm B Page! \n Time now:"+Date.now(), "*");   
        }
    </script>
</body>
</html>

结果示例图

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/sqLeiQ/article/details/115401420
今日推荐