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