HTML5中的postmessage 解决跨域小记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lanix516/article/details/80989801

Window.postMessage API的功能是允许程序员跨域在两个窗口/frames间发送数据信息。基本上,它就像跨域的ajax,但是它不是浏览器和服务器之间的交互,它是两个客户端之间的通信。(处理ie6、ie7外,其他浏览器都支持)

postMessage方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本文档、多窗口,跨域消息传递。

现在有 a.html, b.html两个页面来自不同域,现在假设要在a.html页面中接受从b.html中发送的消息,则在a.html中加入

window.onmessage = function(e){console.log(e)}  , 创建监听方法。

在b.html中发送消息, 使用 Awindow.postmessage(message, targetOrigin)

此时注意,在b.html中调用postmessage时,必须先获得a.html的window窗口对象,使用Awindow调用postmessage。

可以使用postmessage进行消息传递的两种情况,

1. a.html中包含<iframe src='b.html'>, 首先从a页面创建消息回掉函数进行事件监听,然后从b页面发送消息到a页面,需要先找到a页面对应的window对象,在b中调用,window.parent.postmessage(message, targetOrigin)

2. 在a.html中打开b.html, 此时a,b是chrome浏览器的两个标签页,从b中使用window.opener获得a页面的window对象,

window.opener.postmessage 来发送消息


总结,使用postmessage的关键就是如何从发送消息的页面获得需要接受消息页面的window对象

猜你喜欢

转载自blog.csdn.net/lanix516/article/details/80989801