window.postMessage()--實現js之間通信


1.傳遞數據的postMessage.js:

var userData =[{
    "id":0,
    "name":"張三",
    "age":"12",
},{
    "id":1,
    "name":"張四",
    "age":"13",
},{
    "id":2,
    "name":"張五",
    "age":"14",
}];

window.postMessage(JSON.stringify(userData));

2.引用數據的頁面

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>js之間通信</title>
    </head>
    <body>
        <div>獲取到的內容:
            <p id="result"></p>
        </div>
        <ul class="user_data">
            
        </ul>
        <script src="postMessage.js"></script>
        <script>
            /*
            * postMessage.js中的數據放在的消息隊列里,監聽message獲取到消息
            * 
            */
            window.addEventListener("message",function(event){
                if(event.origin!="http://127.0.0.1:8848"){
                    alert("跨域訪問,不接受");
                }else{//同源的地址
                    console.log("event.origin:",event.origin);
                    console.log(event.data);
                    document.querySelector("#result").innerHTML=event.data;
                }
                
            })
        </script>
    </body>
</html>

3.兼容性

 https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage

 


免責聲明!

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



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