zoukankan      html  css  js  c++  java
  • 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=" 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=" 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将监听消息然后渲染字体

  • 相关阅读:
    因子和阶乘
    周期串
    字符串~键盘错位
    6174问题
    HDU_1015——撬锁,5循环
    HDU_1372——骑士移动,二维空间BFS
    HDU_1372——骑士移动,BFS非模版
    HDU_2001——计算两点之间的距离
    HDU_2212
    HDU_1999——不可摸数
  • 原文地址:https://www.cnblogs.com/qingfengliuyun092815/p/7356798.html
Copyright © 2011-2022 走看看