iframe中子父頁面跨域傳遞信息


在非跨域的情況下,iframe中的子父頁面可以很方便的通訊,但是在跨域的情況下,只能通過window.postMessage()方法來向其他頁面發送信息,其他頁面要通過window.addEventListener()監聽事件來接收信息;

#跨域發送信息

#window.postMessage()語法

otherWindow.postMessage(message, targetOrigin, [transfer]);
  • otherWindow
    其他窗口的一個引用,寫的是你要通信的window對象。
    例如:在iframe中向父窗口傳遞數據時,可以寫成window.parent.postMessage(),window.parent表示父窗口。

  • message
    需要傳遞的數據,字符串或者對象都可以。

  • targetOrigin
    表示目標窗口的源,協議+域名+端口號,如果設置爲“*”,則表示可以傳遞給任意窗口。在發送消息的時候,如果目標窗口的協議、域名或端口這三者的任意一項不匹配targetOrigin提供的值,那麼消息就不會被髮送;只有三者完全匹配,消息纔會被髮送。例如:
    window.parent.postMessage(‘hello world’,‘http://xxx.com:8080/index.html’)
    只有父窗口是http://xxx.com:8080時纔會接受到傳遞的消息。

  • [transfer]
    可選參數。是一串和message 同時傳遞的 Transferable 對象,這些對象的所有權將被轉移給消息的接收方,而發送一方將不再保有所有權。我們一般很少用到。

#跨域接收信息

需要監聽的事件名爲"message"

window.addEventListener('message', function (e) {
    console.log(e.data)  //e.data爲傳遞過來的數據
    console.log(e.origin)  //e.origin爲調用 postMessage 時消息發送方窗口的 origin(域名、協議和端口)
    console.log(e.source)  //e.source爲對發送消息的窗口對象的引用,可以使用此來在具有不同origin的兩個窗口之間建立雙向通信
})

#示例Demo

示例功能:跨域情況下,子父頁面互發信息並接收。

  • 父頁面代碼:
<body>
	<button onClick="sendInfo()">向子窗口發送消息</button>
	<iframe id="sonIframe" src="http://192.168.2.235/son.html"></iframe>
    <script type="text/javascript">

        var info = {
            message: "Hello Son!"
        };
		//發送跨域信息
		function sendInfo(){
			var sonIframe= document.getElementById("sonIframe");
			sonIframe.contentWindow.postMessage(info, '*');
		}
		//接收跨域信息
		window.addEventListener('message', function(e){
				alert(e.data.message);
		}, false);
    </script>
</body>
  • 子頁面代碼
<body>
	<button onClick="sendInfo()">向父窗口發送消息</button>
    <script type="text/javascript">

        var info = {
            message: "Hello Parent!"
        };
		//發送跨域信息
		function sendInfo(){
			window.parent.postMessage(info, '*');
		}
		//接收跨域信息
		window.addEventListener('message', function(e){
				alert(e.data.message);
		}, false);
    </script>
</body>

▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
博客園同步更新地址: https://www.cnblogs.com/willingtolove/p/12358630.html
▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章