傳遞的數據,在傳遞參數的時候須要使用JSON.stringify()方法將對象參數序列化html
目標的源,協議,主機,端口號node
<body> <input type="button" value="點擊發送數據到postmessage_01.html" onclick="sendInfoToAnotherDomain();"/> <iframe width="1200" src="http://localhost:8180"></iframe> <script> function sendInfoToAnotherDomain(){ var personInfo= new Object; // 要發送的數據 personInfo.name='Yuelu'; personInfo.title='Hello'; personInfo.info="World"; var str=JSON.stringify(personInfo); // 獲取iframe var iframe=window.frames[0]; /** * [http description] * @type {[type]} 要發送的數據, 目標url */ // 傳遞數據 iframe.postMessage(str,'http://localhost:8180'); } </script> </body>
<body onload="receiveInfoFromAnotherDomain();"> <p>postmessage_01</p> </body> <script> function receiveInfoFromAnotherDomain(){ //監聽窗口對象的message事件 window.addEventListener("message",function(ev){ //判斷是否來自指定的url if(ev.origin !="http://localhost:8080"){ console.log("the event doesn't come from Domain1!"); return; } console.log(ev.data); //將json字符串轉爲json對象 var personInfoJSON = JSON.parse(ev.data); var name = personInfoJSON.name; var title = personInfoJSON.title; var info = personInfoJSON.info; //構造信息文本並顯示 var personInfoString="從域爲: "+ev.origin+"那裏傳來的數據."+"<br>"; personInfoString+="姓名是: "+name+"<br>"; personInfoString+="標題爲: "+title+"<br>"; personInfoString+="信息爲: "+info+"<br>"; document.body.innerHTML=personInfoString; } ); } </script>