About using PostMessage are generally and iframe combined together with, if you are useless to achieve a cross-domain iframe, please leave a message tell me, very grateful.
The two most important part is postMessage
1. Send message
2. accept message
Requires two pages A and B pages page, the page B to the page message A, the A feedback is received. A is the primary domain. A page B page needs to be introduced by iframe, to a message.
A page: a.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>a页面</title>
</head>
<body>
<script>
// 监听事件
window.addEventListener('message', function(e) {
console.log('listen.....', e);
// 告诉b已经接受到了,然后给他返回。
e.source.postMessage('你要返回的值...', e.origin);
}, false);
</script>
</body>
</html>
B Page: b.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>b页面</title>
</head>
<body>
<iframe id="iframe" src="www.dev.zhangjing.cn/a.html" style="width: 0;height: 0" frameborder="0">
</iframe>
</body>
</html>
<script>
window.onload = function() {
// 给a页面发请求
window.frames[0].postMessage({type:"GET",key:"cms"},'*');
}
window.addEventListener('message', function(e) {
// 接受a反馈的消息
console.log('666', e);
}, false);
</script>
Well, you put the two files into their own servers, the introduction of b iframe address (that is, a page in the address of the server) change it. Then open the address on the server b page, see the developer command line console command.
Normal output should be:
// "god ..." {...}
// "god ..." {...}
// "666", ...} {
or
// "god ..." {...}
// "666", ...} {
Finish.