[转]html5: postMessage解决跨域和跨页面通信的问题

平时做web开发的时候关于消息传递,除了客户端与服务器传值,还有几个经常会遇到的问题:

  1. 多窗口之间消息传递(newWin = window.open(..));
  2. 页面与嵌套的iframe消息传递

postMessage方法

postMessage是html5引入的API可以更方便、有效、安全的解决这些问题。postMessage()方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递。

postMessage(data,origin)方法接受两个参数

  1. data:要传递的数据,

    html5规范中提到该参数可以是JavaScript的任意基本类型或可复制的对象,然而并不是所有浏览器都做到了这点儿,部分浏览器只能处理字符串参数,所以我们在传递参数的时候需要使用JSON.stringify()方法对对象参数序列化,在低版本IE中引用json2.js可以实现类似效果。

  2. origin:字符串参数,指明目标窗口的源,

    协议+主机+端口号[+URL],URL会被忽略,所以可以不写,这个参数是为了安全考虑,someWindow.postMessage()方法只会在someWindow所在的源(url的protocol, host, port)和指定源一致时才会成功触发message event,当然如果愿意也可以将参数设置为"*",someWindow可以在任意源,如果要指定和当前窗口同源的话设置为"/"。

MessageEvent的属性

  • data:顾名思义,是传递来的message
  • source:发送消息的窗口对象
  • origin:发送消息窗口的源(协议+主机+端口号)

示例:

同域父子页面间通讯

父页面a.html:

//> localhost:9011/a.html
<h1 class="header">page A</h1>
<div class="mb20">
<textarea name="ta" id="data" cols="30" rows="5">hello world</textarea>
<button style="font-size:20px;" onclick="send()">post message</button>
</div>
<!-- 不跨域的情况 -->
<iframe src="b.html" id="child" style="display: block; border: 1px dashed #ccc; height: 300px;"></iframe> <script>
function send() {
var data = document.querySelector('#data').value; // 注意: 只会触发当前window对象的message事件
// 也可以访问子页面的window对象,触发子页面的message事件 (window.frames[0].postMessage(...))
// window.postMessage(data, '/');
// data = {name: 'sandy', age: 20, fav: {sing: true, shop: false}}; // 也可以传普通对象
window.frames[0].postMessage(data, '/'); // 触发同域子页面的message事件
//window.frames[0].postMessage(data, 'http://localhost:9022/'); // 触发跨域子页面的messag事件
} // 当前页面执行 window.postMessage(..)
// 或
// 子页面执行 parent.postMessage(...) 都会触发下面的回调, messageEvent.source不同而已
window.addEventListener('message', function(messageEvent) {
var data = messageEvent.data;// messageEvent: {source, currentTarget, data}
console.info('message from child:', data);
}, false);
</script>

子页面b.html

//> localhost:9011/b.html
<h1 class="header">page B</h1> <input type="text" id="inp" value="some contents..">
<button onclick="send()">send</button> <script>
window.addEventListener('message', function(ev) {
// if (ev.source !== window.parent) {return;}
var data = ev.data;
console.info('message from parent:', data);
}, false); function send() {
var data = document.querySelector('#inp').value;
// window.postMessage(data, '*'); // 触发当前页面的message事件
parent.postMessage(data, '*'); // 触发父页面的message事件
// parent.postMessage(data, 'http://localhost:9011/'); // 若父页面的域名和指定的不一致,则postMessage失败
}
</script>

跨域父子页面间通讯

父页面a.html:

//> localhost:9011/a.html
<h1 class="header">page A</h1>
<div class="mb20">
<textarea name="ta" id="data" cols="30" rows="5">hello world</textarea>
<button style="font-size:20px;" onclick="send()">post message</button>
</div>
<!-- 跨域的情况 -->
<iframe src="http://localhost:9022/b.html" id="child" style="display: block; border: 1px dashed #ccc; height: 300px;"></iframe> <script>
function send() {
var data = document.querySelector('#data').value; window.frames[0].postMessage(data, 'http://localhost:9022/'); // 触发跨域子页面的messag事件
} window.addEventListener('message', function(messageEvent) {
var data = messageEvent.data;
console.info('message from child:', data);
}, false);
</script>

子页面b.html

//> localhost:9022/b.html
<h1 class="header">page B</h1> <input type="text" id="inp" value="some contents..">
<button onclick="send()">send</button> <script>
window.addEventListener('message', function(ev) {
// if (ev.source !== window.parent) {return;}
var data = ev.data;
console.info('message from parent:', data);
}, false); function send() {
var data = document.querySelector('#inp').value;
parent.postMessage(data, 'http://localhost:9011/'); // 若父页面的域名和指定的不一致,则postMessage失败
// parent.postMessage(data, '*'); // 触发父页面的message事件
}
</script>

[转]html5: postMessage解决跨域和跨页面通信的问题的更多相关文章

  1. html5 postMessage解决跨域、跨窗口消息传递

    一些麻烦事儿 平时做web开发的时候关于消息传递,除了客户端与服务器传值还有几个经常会遇到的问题 1.页面和其打开的新窗口的数据传递 2.多窗口之间消息传递 3.页面与嵌套的iframe消息传递 4. ...

  2. html5 postMessage解决跨域、跨窗口消息传递[转载]

    原文:http://www.cnblogs.com/dolphinX/p/3464056.html 一些麻烦事儿 平时做web开发的时候关于消息传递,除了客户端与服务器传值还有几个经常会遇到的问题 1 ...

  3. html5 postMessage解决跨域、跨窗口消息传递(转)

    仅做学习使用,原文链接:http://www.cnblogs.com/dolphinX/p/3464056.html 一些麻烦事儿 平时做web开发的时候关于消息传递,除了客户端与服务器传值还有几个经 ...

  4. html5 postMessage解决iframe跨协议跨域通信问题

    a.html有个iframe载入b.com/login.html,当login完成时通知a.html页面登录完成并传递UserName 1.a.html 监听消息 window.addEventLis ...

  5. Django跨域(前端跨域)

    前情回顾 在说今天的问题之前先来回顾一下有关Ajax的相关内容 Ajax的优缺点 AJAX使用Javascript技术向服务器发送异步请求: AJAX无须刷新整个页面: 因为服务器响应内容不再是整个页 ...

  6. 跨域解决方案 - 跨域资源共享cors

    目录 1. cors 介绍 2. 原理 3. cors 解决跨域 4. 自定义HTTP 头部字段解决跨域 5. 代码演示 5. 参考链接 1. cors 介绍 cors 说的是一个机制,其实相当于一个 ...

  7. 能跨域和跨浏览器的flashcookie for jquery插件

    对于写网站时需要跨域和跨浏览器的可以看看这个. 引入jquery  和 swfstore.min.js 就可以了,蛮简单好用的,会jquery基础就可以咯. mySwfStore.set('myKey ...

  8. localstrage、cookie、session等跨域和跨页面监听更新问题

    localstrage.cookie.session等跨域和跨页面监听更新问题

  9. html5: postMessage解决跨域通信的问题

    效果图 postmessage解析 HTML5提供了新型机制PostMessage实现安全的跨源通信. 语法 otherWindow.postMessage(message, targetOrigin ...

随机推荐

  1. js点击回到顶部2

    <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>点 ...

  2. pythonweb服务器编程(四)

    Web动态服务器-1 #coding=utf-8 import socket import sys from multiprocessing import Process import re clas ...

  3. Charles抓包(未完待续)

    Charles是在 Mac 下常用的网络封包截取工具,在做移动开发时,我们为了调试与服务器端的网络通讯协议,常常需要截取网络封包来分析. Charles 通过将自己设置成系统的网络访问代理服务器,使得 ...

  4. linux 修改时间和时区

    linux系统时间有两个,一个是硬件时间,即BIOS时间,就是我们进行CMOS设置时看到的时间,另一个是系统时间,是linux系统Kernel时间.当Linux启动时,系统Kernel会去读取硬件时钟 ...

  5. Sublime_SublimeServer

    1. 遇到问题:如下代码第17行,获取本地json文件,如果直接在浏览器中打开引用该文件的.html文件,在chrme浏览器中并不能读取到json文件. var vm=new Vue({ el:&qu ...

  6. javascript中的常用表单事件用法

    下面介绍几种javascript中常用的表单事件: 一,onsubmit:表单中的确认按钮被点击时发生的事件,如下案例. 案例解析:弹出表单中提交的内容 <form name="tes ...

  7. Cocos Creator脚本开发事例

    HelloWorld.js window.Global = { gint: 168, }; cc.Class({ extends: cc.Component, properties: { label: ...

  8. SpringCloud无废话入门02:Ribbon负载均衡

    1.白话负载均衡 在上一篇的介绍中,我们创建了两个一模一样的服务提供者:Provider1和Provider2,然后它们提供的服务也一模一样,都叫Hello-Service.为什么一样的服务我们要部署 ...

  9. javascript日期时间操作库推荐

    https://github.com/datejs/Datejs 链接: https://pan.baidu.com/s/1QTGhxslarNyW_0kB6gyJYA 提取码: ibab 如果这篇文 ...

  10. 图解Windows下 GIT GUI 使用教程

    https://jingyan.baidu.com/article/19020a0a7ae6af529c284248.html 本篇经验将和大家介绍Windows下 GIT GUI 使用教程,希望对大 ...