今天遇到一个和同事合作的项目,同事说:XXX的时候 postmessage 给我,当场一脸懵逼,这是什么???
查了一下文档,如下:

The window.postMessage method safely enables cross-origin communication. Normally, scripts on different pages are allowed to access each other if and only if the pages that executed them are at locations with the same protocol (usually both https), port number (443 being the default for https), and host (modulo document.domain being set by both pages to the same value). window.postMessage provides a controlled mechanism to circumvent this restriction in a way which is secure when properly used.

翻译一下,就是 window.postMessage 可以绕过同源策略来安全的进行不同页面间的通信。

语法

otherWindow.postMessage(message, targetOrigin);

otherWindow: 指目标窗口,也就是给哪个window发消息。
message: 要发送的消息,类型为 String、Object (IE8、9 不支持)。
targetOrigin: 限定消息接收范围,如果不限制,可以使用 *

实践

开2个文件来试试~

发送:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>req</title>
</head>
<body>
<script type="text/javascript">
var domain = 'http://www.resmessage.com:8080';
var resWindow = window.open(domain + '/resTest.html', 'resWindow');

var message = 'Hello';
resWindow.postMessage(message, domain);

//监听消息反馈
window.addEventListener('message', function(event) {
console.log('received response: ', event.data);
}, false);
</script>
</body>
</html>

接收:
(接收页地址为http://www.resmessage.com:8080/resTest.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>res</title>
</head>
<body>
<script type="text/javascript">
window.addEventListener('message', function(event) {
console.log('message received: ' + event.data, event);
event.source.postMessage('Helloooo!', event.origin);
}, false);
</script>
</body>
</html>