• 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将监听消息然后渲染字体

  • 相关阅读:
    Python 面向对象4-特殊成员
    Python 面向对象3-成员修饰符
    Python 面向对象2
    Python 面向对象
    Python hashlib模块
    使用Access-Control-Allow-Origin解决跨域
    倒计时
    移动端之touch事件--手指的滑动事件
    HTML5获取地理经纬度并通过百度接口得到实时位置
    h5直播
  • 原文地址:https://www.cnblogs.com/qingfengliuyun092815/p/7356798.html
Copyright © 2020-2023  润新知