六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 111|回复: 0

postMessage实现跨文档消息传输

[复制链接]

升级  28.33%

79

主题

79

主题

79

主题

举人

Rank: 3Rank: 3

积分
285
 楼主| 发表于 2013-1-24 06:46:32 | 显示全部楼层 |阅读模式
在HTML5中新增了postMessage方法,postMessage可以实现跨文档消息传输(Cross Document Messaging),Internet Explorer 8, Firefox 3, Opera 9, Chrome 3和 Safari 4都支持postMessage。

/* * In window A's scripts, with A being on <http://example.com:8080>: */var popup = window.open(...popup details...);// When the popup has fully loaded, if not blocked by a popup blocker:// This does nothing, assuming the window hasn't changed its location.popup.postMessage("The user is 'bob' and the password is 'secret'","https://secure.example.net");// This will successfully queue a message to be sent to the popup, assuming// the window hasn't changed its location.function receiveMessage(event){  // Do we trust the sender of this message?  (might be  // different from what we originally opened, for example).  if (event.origin !== "http://example.org") return;  // event.source is popup  // event.data is "hi there yourself!  the secret response is: rheeeeet!"}window.addEventListener("message", receiveMessage, false);
可以通过绑定window的message事件来监听发送跨文档消息传输内容

setTimeout经常被用来做网页上的定时器,允许为它指定一个毫秒数作为间隔执行的时间。当被启动的程序需要在非常短的时间内运行,我们就会给她指定一个很小的时间数,或者需要马上执行的话,我们甚至把这个毫秒数设置为0,但事实上,setTimeout有一个最小执行时间,当指定的时间小于该时间时,浏览器会用最小允许的时间作为setTimeout的时间间隔,也就是说即使我们把setTimeout的毫秒数设置为0,被调用的程序也没有马上启动。
postMessage实现无延迟的setTimeout基本思路是:将要调用的函数加入数组中,并马上向自己所在的窗口发一个消息,对窗口添加了接收消息事件,所以窗口马上就收到了该消息,接着就将之前数组中保存的函数弹出并执行。也就是绑定window窗体message事件去侦听这个事件。
// BEGIN implementation of setZeroTimeout// Only add setZeroTimeout to the window object, and hide everything// else in a closure.(function() {var timeouts = [];var messageName = "zero-timeout-message";// Like setTimeout, but only takes a function argument.  There's// no time argument (always zero) and no arguments (you have to// use a closure).function setZeroTimeout(fn) {timeouts.push(fn);window.postMessage(messageName, "*");}function handleMessage(event) {if (event.source == window && event.data == messageName) {event.stopPropagation();if (timeouts.length> 0) {var fn = timeouts.shift();fn();}}}window.addEventListener("message", handleMessage, true);// Add the one thing we want added to the window object.window.setZeroTimeout = setZeroTimeout;})();

外部调用方法来触发事件,此时触发内部message事件绑定handleMessage方法。
window.setZeroTimeout(function(){})

参考:
https://developer.mozilla.org/en/DOM/window.postMessage
http://blog.tugai.net/2010/03/27/postmessage-settimeout/
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表