Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

html5的postMessage无法接收到数据

今天在学习跨域访问的时候,测试了html5的postmessage的使用,遇到了无法接收的问题,从一个页面向页面中的iframe发送数据,无法发送。查阅了很多资料,感觉使用也没有出错,不知道问题出在哪里,希望用过的大牛帮忙看下,下面附上代码:

test.html文件(发送页面)

<iframe name="receive" id="iframe" src="test2.html" >

</iframe>
<script type="text/javascript">

window.onload=function() {
    window.postMessage('收到没', '*');//在这里发送数据

}
</script>

test2.html文件(接收页面)

<script>
    window.addEventListener("message",function(e){
        alert(e.data);
    })

</script>

刷新页面,无法获得alert消息,我在本地服务器下面同一个文件夹里,主页面和iframe应该是处于同一个域下的,不理解为什么同域就出问题了。

PS:发送应该没有问题,因为自发自收是没问题的

<iframe name="receive" id="iframe" src="test2.html" >

</iframe>
<script type="text/javascript">

window.onload=function() {
    window.postMessage('收到没', '*');
    window.addEventListener("message",function(e){
        alert(e.data);
    })

}
</script>

图片描述


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

你在test.html中使用的window.postMessage语法中的window其实是指你要发送的目标窗口对象

所以你这里直接拿window用就代表当前窗口,而你当前test.html的窗口中没有监听message事件,所以没办法触发test2.html中的alert

所以你应该这么做,把test.html中window.postMessage中的window用iframe的name来代替

receive.postMessage(....)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...