VUE组件如何与iframe通信问题

vue组件内嵌一个iframe,现在想要在iframe内获取父vue组件内信息,由于本人技术有限,采用的是H5新特性PostMessage来解决跨域问题。

postMessage内涵两个API:

onMessage:消息监听

postMessage:消息发送

举个栗子,比如我要改变iframe内字体变成跟父级一样,直接上代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    
</head>

<body>

    <div id="father" class="father" style="width: 100px;height: 100px;border: solid 1px #333;color: blue;" onclick="sentPost()">
        <div>father</div>
    </div>
    
    <iframe src="son.html" id="son"></iframe>
    
    <script type="text/javascript">
        function sentPost() {
            var iframeWin = document.getElementById('son').contentWindow;
            iframeWin.postMessage(document.getElementById("father").style.color, "*");
        }
        window.addEventListener("message",function(event){
            console.log(event,event.data);
        },false);
    </script>
</body>
</html>

以上代码将父级字体的颜色发送到子iframe;

子iframe代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="container" style="width: 200px;height: 200px;color: red;">son</div>
    <script type="text/javascript">
        window.addEventListener("message", function(event){
            console.log(event);
            var color = event.data;
            document.getElementById("container").style.color = color;
        },false);
    </script>
</body>
</html>

子iframe将监听消息然后渲染字体

posted @ 2017-08-14 11:24  清风·流云  阅读(3881)  评论(0编辑  收藏  举报