【JS】postMessage
最近有個需求,需要iframe cross domain
架構如下:
最外層的頁面是屬於內網,不對外開放,這裡稱他為父頁面
而需內嵌一個頁面,來自http://www.example.com,使用Iframe內嵌
但是IframeA需跟父頁面發送消息。
譬如這是此次IframeA需要帶過去的資料 itemID = 200
如果用傳統作法event發送,會有cross domain的問題
所以改用html5的postMessage來做
官方文件如下:
用法也相當簡單:
otherWindow.postMessage(message, targetOrigin, [transfer])
*message ---- 準備帶過去的資料
資料類型可以參考下面官方提供的文檔
可以是string,object,json...等等
這次用的範例是一個object
*tagetOrigon ---- 就是用來驗證是否是合法的用戶,
跟以前的crossdomain.xml有異曲同工之妙
在接收端的部分可以用event.origin來驗證來源是否是自己允許的對象
在來進行接下來邏輯操作
_____________________________________________________________________________
IfameA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//資料送出 | |
<script> | |
sendItemMsg(40012); | |
function sendItemMsg(itemID) | |
{ | |
var obj = {opcode:99,id:itemID}; | |
window.parent.postMessage(obj, "*"); | |
} | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
window.addEventListener("message", receiveMessage, false); | |
function receiveMessage(event) | |
{ | |
alert("[origin]:"+event.origin +", [op]:"+event.data.opcode +", [id]:"+event.data.id); | |
if(event.origin!=="http://www.example.com") | |
{ | |
return; | |
} | |
} | |
</script> |
張貼留言