html5 cross-domain communication postMessage

黄舟
Release: 2017-02-16 14:30:48
Original
1690 people have browsed it

How to use postMessage in html5 cross-domain communication

Documents under different domain names are not allowed to access each other's documents due to security issues, but some Sometimes it is necessary to do this. Therefore, we can generally use window.name, hash, or jsonp to achieve cross-domain access.

But since HTML5 came out, we can have one more way to implement postMessage. The following is the simplest example of message passing. The function we want to implement is to send the content in page1 to different Page2 page under the domain name, and then page2 will display the corresponding message content.

The following are several important event attributes:

  • source – message source, message sending window/iframe.

  • origin – URI of the message source (may include protocol, domain name and port), used to verify the data source.

  • data – Data sent by the sender to the receiver.
    These three attributes are data that must be used in message transmission.

First we need two pages, and then they must be located under different domain names. Of course, this machine must have a web server. Next, we will modify the host to achieve different domain name access

127.0.0.1 www.postmessage1.com127.0.0.1 www.postmessage2.com
Copy after login
Copy after login

The homepage //m.sbmmt.com/ has an iframe nested inside it

 Html5 postMessage跨文档通信
Copy after login
Copy after login

The src address of the iframe is //m.sbmmt.com/

 

我是一个iframe

Copy after login
Copy after login

html5 cross-domain communication postMessage

Like many other web technologies, if you do not verify the legitimacy of the data source, then using this technology will become very dangerous; the security of your application requires you to It's responsible. window.postMessage is like PHP versus JavaScript technology. window.postMessage is cool, isn't it?

The two-way data transmission is the same:

 Html5 postMessage跨文档通信
Copy after login
Copy after login

The code of the other page is as follows:

 

我是一个iframe

Copy after login
Copy after login

html5 cross-domain communication postMessage

2. Channel communication

The message channel provides a direct, two-way communication method between browsing contexts. Like cross-document communication, the DOM is not directly exposed. Instead, each end of the pipe is a port, and data is sent from one port and received by the other.

Message channels are useful, especially for communication across multiple origins. Please consider the following situation:
Renren.com (//m.sbmmt.com/) embeds a third-party game page (through iframe, such as "Renren Restaurant"). At the same time, this third-party The game page (//m.sbmmt.com/) needs to obtain the user's communication information from another address book website (//m.sbmmt.com/). What to do?

That is to say, the address book site needs to send information to the game site. According to cross-document communication, we let the parent page serve as the proxy (that is, the Renren page here) (similar to the first demo). However, this approach means that address book sites need to have the same level of trust as Renren pages. Renren, a social networking site, needs to trust every request, or filter it for us (should refer to: specify one by one).

However, using channel communication, the address book site (//m.sbmmt.com/) and the game site (//m.sbmmt.com/) candirectly communicate.

MessageChannel and MessagePort objects

When we create a MessageChannel object, we actually create two interconnected ports. One port remains open for the sending end. The other one is forwarded to other browsing contexts (sent by the parent page to another child page of the iframe element).

var mc = new MessageChannel();
Copy after login
Copy after login

Each port is a MessagePort object, including 3 available methods:

  • postMessage() Send a message through the channel

  • start() Start dispatching received messages on the port

  • close() Close the port

The MessagePort object also has the onmessage event attribute, Can be used to define event handlers instead of event listeners.

Examples
I can’t understand the jargon-y stuff above, but it’s easier to explain with examples.

First create three websites, the main website is: //m.sbmmt.com/, and two other sub-websites //m.sbmmt.com/ and http://www. php.cn/. Now let’s simulate the communication process between two sub-websites:

Requirements: When sub-website 1 is loaded, send a message to sub-website 2: "(1) I can’t wait, are you okay? ?
", when sub-website 2 receives the message, it returns a message to sub-website 1, "(2) Don't worry, it will be there soon!" When sub-webpage 1 receives the message from sub-website 2, it returns the dialogue information to the main page.

Code of sub-page 1

 通道通信子页面iframe01
Copy after login
Copy after login

Code of main page:

 messageChannel通信

通道通信实例

Copy after login
Copy after login

Code of subpage 2:

 通道通信子页面iframe02
Copy after login
Copy after login

Result image
html5 cross-domain communication postMessage

The above demo uses three pages: the main page and two iframe pages. Let’s talk about what each page does:

The first is the first iframe page: it has three tasks,

  • 一是创建MessageChannel通道对象;

  • 二是告诉主页面,我加载好了,并把端口传过去;

  • 三是显示发送信息。

//1.创建MessageChannel通道对象mc = new MessageChannel();//2.二是告诉主页面,我加载好了,并把端口传过去;window.parent.postMessage('(1)我已经等不及了,你好了吗?
', 'http://localhost/test1/main.html', [mc.port2]);//3.显示发送信息mc.port1.addEventListener('message', portMessageHandler, false); mc.port1.start();
Copy after login
Copy after login

主页面其任务很简单就一个:告诉第二个iframe页面,端口已经打开了(第一个iframe就可以确定跟第二个iframe通信的端口了)。

// 将端口告诉其他文档iframes[1].postMessage(event.data,'http://localhost/test2/iframe02.html', event.ports);
Copy after login
Copy after login

最后就是第二个iframe页面。其任务有两个:一是确定接到的消息与端口;二是将post一个新的数据和此端口保持通信了。

// 1. 接到消息与端口window.addEventListener('message',messageHandler, false);// 2. 与端口建立通道,post一个新的数据port.postMessage(message);
Copy after login
Copy after login

html5跨域通信之postMessage的用法

不同域名下的文档因为安全问题,不允许相互之间文档的访问,但是有的时候却不得不需要这样的操作。因此我们一般可以采用 window.name,hash,或者jsonp来实现跨域访问。

不过自从html5出来以后,我们又可以多一种实现方式了postMessage,下面就是一个最简单的消息传递的例子,我们要实现的功能是将page1页面中的内容,发送到不同域名下的page2页面,然后page2将对应消息内容展示出来。

下面是几个比较重要的事件属性:

  • source – 消息源,消息的发送窗口/iframe。

  • origin – 消息源的URI(可能包含协议、域名和端口),用来验证数据源。

  • data – 发送方发送给接收方的数据。
    这三个属性是消息传输中必须用到的数据。

首先我们需要两个页面,然后必须分别位于不同的域名下,当然本机肯定要有一个web服务器,接下来就通过修改host来实现不同域名访问

127.0.0.1 www.postmessage1.com127.0.0.1 www.postmessage2.com
Copy after login
Copy after login

主页//m.sbmmt.com/ 里面嵌套一个iframe框架

 Html5 postMessage跨文档通信
Copy after login
Copy after login

iframe框架的src地址为//m.sbmmt.com/

 

我是一个iframe

Copy after login
Copy after login

html5 cross-domain communication postMessage

跟其他很web技术一样,如果你不校验数据源的合法性,那使用这种技术将会变得很危险;你的应用的安全需要你对它负责。window.postMessage就像是PHP相对于JavaScript技术。window.postMessage很酷,不是吗?

双向数据传输也是一样的:

 Html5 postMessage跨文档通信
Copy after login
Copy after login

另一个页面的代码如下:

 

我是一个iframe

Copy after login
Copy after login

html5 cross-domain communication postMessage

2.通道通信

消息通道提供了一个直接,双向浏览上下文之间的通信手段。跟跨文档通信一样,DOM不直接暴露。取而代之,管道每端为端口,数据从一个端口发送,被另一个端口接收,。

消息通道是有用的,特别是跨多个起源的沟通。请考虑以下情形:
人人网上(//m.sbmmt.com/)嵌入了一个第三方的游戏页面(通过iframe的形式,如“人人餐厅”),同时,这个第三方的游戏页面(//m.sbmmt.com/)又需要从另外一个通讯录网站(//m.sbmmt.com/)获取用户的通讯信息。咋办?

也就是说通讯录站点要发送信息给游戏站点,根据跨文档通信,我们让父页面作为代理(也就是这里的人人网页面)(类似第一个demo)。然而,这种做法意味着通讯录站点需要有和人人网页面一样的信任级别。人人网这个社交站点需要信任每一个请求,或者为我们过滤(应该指:一个一个指定)。

但是,使用通道通信,通讯录站点(//m.sbmmt.com/)和游戏站点(//m.sbmmt.com/)可以直接沟通

MessageChannel和MessagePort对象

当我们创建了一个MessageChannel对象,我们实际上创造了两个相互关联的端口。一个端口保持开放,为发送端。另外一个被转发到其他浏览上下文(被父页面发送到另外一个iframe元素的子页面中)。

var mc = new MessageChannel();
Copy after login
Copy after login

每一个端口就是一个MessagePort对象,包含3个可用方法:

  • postMessage() 通过通道发送消息

  • start() 开始在端口上分派接受的信息

  • close() 关闭端口

MessagePort对象还有onmessage事件属性,可被用来定义事件句柄而不是事件监听。

实例
上面过于术语的东西我自己都看不明白,还是实例好说话。

首先建立三个网站,其中主网站为://m.sbmmt.com/,另外建立两个子网站//m.sbmmt.com/和//m.sbmmt.com/。现在来模拟两个子网站之间的通信过程:

需求:当子网站1被加载完成后,向子网站2发送消息:“(1)我已经等不及了,你好了吗?
”,当子网站2接收到消息后,向子网站1返回消息,“(2)你别急呀,马上就好!”。当子网页1接收到子网站2 的消息后,返回给主页面页面对话信息.

子页面1的代码

 通道通信子页面iframe01
Copy after login
Copy after login

主页面的代码:

 messageChannel通信

通道通信实例

Copy after login
Copy after login

子页面2的代码:

 通道通信子页面iframe02
Copy after login
Copy after login

结果图
html5 cross-domain communication postMessage

上面的demo动用了三个页面:主页面和两个iframe页面。下面说说每个页面都做了些什么:

首先是第一个iframe页面:其任务有三个,

  • 一是创建MessageChannel通道对象;

  • 二是告诉主页面,我加载好了,并把端口传过去;

  • 三是显示发送信息。

//1.创建MessageChannel通道对象mc = new MessageChannel();//2.二是告诉主页面,我加载好了,并把端口传过去;window.parent.postMessage('(1)我已经等不及了,你好了吗?
', 'http://localhost/test1/main.html', [mc.port2]);//3.显示发送信息mc.port1.addEventListener('message', portMessageHandler, false); mc.port1.start();
Copy after login
Copy after login

主页面其任务很简单就一个:告诉第二个iframe页面,端口已经打开了(第一个iframe就可以确定跟第二个iframe通信的端口了)。

// 将端口告诉其他文档iframes[1].postMessage(event.data,'http://localhost/test2/iframe02.html', event.ports);
Copy after login
Copy after login

最后就是第二个iframe页面。其任务有两个:一是确定接到的消息与端口;二是将post一个新的数据和此端口保持通信了。

// 1. 接到消息与端口window.addEventListener('message',messageHandler, false);// 2. 与端口建立通道,post一个新的数据port.postMessage(message);
Copy after login
Copy after login

以上就是html5跨域通信之postMessage的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!