一、使用postMessage在irfame中實現跨域數據傳遞
1、父頁面內容
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <h1>主頁面</h1> <iframe id="child" src="http://10.0.0.159:8080"></iframe> <div> <h2>主頁面跨域接收消息區域</h2> <div id="message"></div> </div> </body> <script> /* -------------iframe跨域數據傳遞--------------- */ //傳遞數據到子頁面 window.onload = function() { document.getElementById('child').contentWindow.postMessage("主頁面消息", "http://10.0.0.159:8080") } //接受子頁面傳遞過來的數據 window.addEventListener('message', function(event) { document.getElementById('message').innerHTML = "收到" + event.origin + "消息:" + event.data; }, false); </script> </html>
2、子頁面
(我這里在在vue頁面里做的測試,vue模板的html代碼就不展示了)
mounted() { //接收父頁面傳過來的數據 window.addEventListener('message', function(event) { // 處理addEventListener執行兩次的情況,避免獲取不到data // 因此判斷接收的域是否是父頁面 if(event.origin.includes("http://127.0.0.1:8848")){ console.log(event); document.getElementById('message').innerHTML = "收到" + event.origin + "消息:" + event.data; //把數據傳遞給父頁面 > top.postMessage(要傳遞的數據,父頁面的url訪問地址) top.postMessage("子頁面消息收到", 'http://127.0.0.1:8848/boatStaticHtml/iframe%E9%80%9A%E4%BF%A1.html'); } }, false); }
3、效果圖展示
二、postMessage在window.open()中的使用
1、第一種方式,兩個頁面之前數據的相互傳遞
父頁面:parent.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script src="js/jquery-3.1.1.min.js" type="text/javascript"></script> <script type="text/javascript"> function openWin() { var params = new Array(); params[0] = new Array("params1", "aaaaaa"); params[1] = new Array("params2", "bbbbbb"); var popupwin = window.open("child.html"); //onload只能執行一次,也就是如果子窗口有onload事件,可能會覆蓋。 popupwin.onload = function(e){ popupwin.postMessage(params, "http://127.0.0.1:8848/"); } popupwin.onunload = function(e){ var val = popupwin.returnValue; alert(val); } } </script> </head> <body> <input type="button" value="打開新頁面" onclick="openWin()" /> </body> </html>
子頁面:child.html
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>popup window</title> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script language="javascript" type="text/javascript"> function closeWin() { window.returnValue = true; window.close(); } document.onreadystatechange = function(e) { if (document.readyState === 'complete') { window.addEventListener('message', function(e){ var params = e.data; $('#params1').text(params[0][1]); $('#params2').text(params[1][1]); }); } }; </script> </head> <body> <h3>Parameter params1: <b id="params1"></b></h3> <h3>Parameter params2: <b id="params2"></b></h3> <div><input type="button" value="Return Value" onclick="closeWin()" /></div> </body> </html>
效果如下:
2、第二種方式:
//-----父頁面------ //打開新頁面 window.open(); //監聽新頁面傳遞過來的數據 window.addEventListener('message', function(event) { console.log(event.data); }, false); //子頁面數據傳遞方式,這個方式需要通過事件來傳遞 setTimeout(function(){ window.opener.postMessage({ isColse: 'ok' }, '*'); },2000)