postMessage是H5的API,用来解决跨页面通信的。postMessage的使用分为发送方和接收方。
发送方的代码用法如下:
otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow是接收方的window对象。可以通过以下几种方法获得,例如window.open()方法返回的值就是打开页面的window对象,或者iframe元素的contentWindow属性能获得iframe标签内页面的window对象,等等。
message是你要发送到其他 window的数据。
targetOrigin是接收方域,即接收方页面的window.origin属性。如果接收方窗口的协议、主机地址或端口这三者的任意一项不匹配targetOrigin提供的值,那么消息就不会被发送。该参数也可以是‘*’,表示对接收方的域没有任何限制。
[transfer]是可选项,数组内的对象是实现Transferable接口的对象。它和message一样会被传递给目标页面,这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。
接收方要开启事件监听,监听message事件,接收方的代码如下:
window.addEventListener("message", receiveMessage, false); function receiveMessage(event) { var origin = event.origin; if (origin !== "http://example.org:8080")// 假设接受方只接受来自http://example.org:8080域的信息 return; // ... }
这里的event是MessageEvent的实例,里面包含了data、origin、source属性。data是发送方发送的message,origin是发送方所属的域,source是发送方的window对象的引用。
案例以后在进行补充...
更多详情请看MDN,链接地址: https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage