HTML5的的postMessage的使用手册的使用手册
我们在码代码的时候,经常会碰到以下跨域的情况:
1、页面内嵌套iframe,与iframe的消息传递
2、页面与多个页面之间的传递消息
针对这些令人头疼的跨域问题,html5特地推出新功能–postMessage(跨文档消息传输)。postMessage在使用时,需要传入2个参数,data
和originUrl。data是指需要传递的内容,但是部分浏览器只能处理字符串参数,所以我们一般把data序列化一下,即
JSON.stringify(),originUrl是指目标url,指定的窗口。
下面直接甩例子,相信大家更容易理解写。
1、页面内嵌套iframe
父页面:
html:
<div id='parent'>hello word postMessage</div>
<iframe src="http://127.0.0.1:8082/index2.html" id='child'></iframe>
js:
window.onload=function(){
window.frames[0].postMessage('postMessage','http://127.0.0.1:8082/index2.html')
}
window.addEventListener('message',function(e){
console.log(e)
document.getElementById('parent').style.color=e.data
})
子页面:
html:
<div id='button' onclick='changeColor();' style="color:yellow">接受信息</div>
js:
window.addEventListener('message',function(e){
console.log(e)
let color = document.getElementById('button').style.color
window.parent.postMessage(color,'http://127.0.0.1:8081/index.html')
});
function changeColor(){
let buttonColor = document.getElementById('button').style.color
buttonColor='#f00'
window.parent.postMessage(buttonColor,'http://127.0.0.1:8081/index.html')
}
父页面通过postMessage的方法向iframe传递消息,而子页面通过window.addEventListener监听message方法来获取到父页面传递的值。
如下图所示,data是父页面传递的值。