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將監聽消息然后渲染字體


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM