postmessage.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. /**
  2. The MIT License
  3. Copyright (c) 2010 Daniel Park (http://metaweb.com, http://postmessage.freebaseapps.com)
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. **/
  20. var NO_JQUERY = {};
  21. (function(window, $, undefined) {
  22. if (!("console" in window)) {
  23. var c = window.console = {};
  24. c.log = c.warn = c.error = c.debug = function(){};
  25. }
  26. if ($ === NO_JQUERY) {
  27. // jQuery is optional
  28. $ = {
  29. fn: {},
  30. extend: function() {
  31. var a = arguments[0];
  32. for (var i=1,len=arguments.length; i<len; i++) {
  33. var b = arguments[i];
  34. for (var prop in b) {
  35. a[prop] = b[prop];
  36. }
  37. }
  38. return a;
  39. }
  40. };
  41. }
  42. $.fn.pm = function() {
  43. console.log("usage: \nto send: $.pm(options)\nto receive: $.pm.bind(type, fn, [origin])");
  44. return this;
  45. };
  46. // send postmessage
  47. $.pm = window.pm = function(options) {
  48. pm.send(options);
  49. };
  50. // bind postmessage handler
  51. $.pm.bind = window.pm.bind = function(type, fn, origin, hash, async_reply) {
  52. pm.bind(type, fn, origin, hash, async_reply === true);
  53. };
  54. // unbind postmessage handler
  55. $.pm.unbind = window.pm.unbind = function(type, fn) {
  56. pm.unbind(type, fn);
  57. };
  58. // default postmessage origin on bind
  59. $.pm.origin = window.pm.origin = null;
  60. // default postmessage polling if using location hash to pass postmessages
  61. $.pm.poll = window.pm.poll = 200;
  62. var pm = {
  63. send: function(options) {
  64. var o = $.extend({}, pm.defaults, options),
  65. target = o.target;
  66. if (!o.target) {
  67. console.warn("postmessage target window required");
  68. return;
  69. }
  70. if (!o.type) {
  71. console.warn("postmessage type required");
  72. return;
  73. }
  74. var msg = {data:o.data, type:o.type};
  75. if (o.success) {
  76. msg.callback = pm._callback(o.success);
  77. }
  78. if (o.error) {
  79. msg.errback = pm._callback(o.error);
  80. }
  81. if (("postMessage" in target) && !o.hash) {
  82. pm._bind();
  83. target.postMessage(JSON.stringify(msg), o.origin || '*');
  84. }
  85. else {
  86. pm.hash._bind();
  87. pm.hash.send(o, msg);
  88. }
  89. },
  90. bind: function(type, fn, origin, hash, async_reply) {
  91. pm._replyBind ( type, fn, origin, hash, async_reply );
  92. },
  93. _replyBind: function(type, fn, origin, hash, isCallback) {
  94. if (("postMessage" in window) && !hash) {
  95. pm._bind();
  96. }
  97. else {
  98. pm.hash._bind();
  99. }
  100. var l = pm.data("listeners.postmessage");
  101. if (!l) {
  102. l = {};
  103. pm.data("listeners.postmessage", l);
  104. }
  105. var fns = l[type];
  106. if (!fns) {
  107. fns = [];
  108. l[type] = fns;
  109. }
  110. fns.push({fn:fn, callback: isCallback, origin:origin || $.pm.origin});
  111. },
  112. unbind: function(type, fn) {
  113. var l = pm.data("listeners.postmessage");
  114. if (l) {
  115. if (type) {
  116. if (fn) {
  117. // remove specific listener
  118. var fns = l[type];
  119. if (fns) {
  120. var m = [];
  121. for (var i=0,len=fns.length; i<len; i++) {
  122. var o = fns[i];
  123. if (o.fn !== fn) {
  124. m.push(o);
  125. }
  126. }
  127. l[type] = m;
  128. }
  129. }
  130. else {
  131. // remove all listeners by type
  132. delete l[type];
  133. }
  134. }
  135. else {
  136. // unbind all listeners of all type
  137. for (var i in l) {
  138. delete l[i];
  139. }
  140. }
  141. }
  142. },
  143. data: function(k, v) {
  144. if (v === undefined) {
  145. return pm._data[k];
  146. }
  147. pm._data[k] = v;
  148. return v;
  149. },
  150. _data: {},
  151. _CHARS: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''),
  152. _random: function() {
  153. var r = [];
  154. for (var i=0; i<32; i++) {
  155. r[i] = pm._CHARS[0 | Math.random() * 32];
  156. };
  157. return r.join("");
  158. },
  159. _callback: function(fn) {
  160. var cbs = pm.data("callbacks.postmessage");
  161. if (!cbs) {
  162. cbs = {};
  163. pm.data("callbacks.postmessage", cbs);
  164. }
  165. var r = pm._random();
  166. cbs[r] = fn;
  167. return r;
  168. },
  169. _bind: function() {
  170. // are we already listening to message events on this w?
  171. if (!pm.data("listening.postmessage")) {
  172. if (window.addEventListener) {
  173. window.addEventListener("message", pm._dispatch, false);
  174. }
  175. else if (window.attachEvent) {
  176. window.attachEvent("onmessage", pm._dispatch);
  177. }
  178. pm.data("listening.postmessage", 1);
  179. }
  180. },
  181. _dispatch: function(e) {
  182. //console.log("$.pm.dispatch", e, this);
  183. try {
  184. var msg = JSON.parse(e.data);
  185. }
  186. catch (ex) {
  187. //console.warn("postmessage data invalid json: ", ex); //message wasn't meant for pm
  188. return;
  189. }
  190. if (!msg.type) {
  191. //console.warn("postmessage message type required"); //message wasn't meant for pm
  192. return;
  193. }
  194. var cbs = pm.data("callbacks.postmessage") || {},
  195. cb = cbs[msg.type];
  196. if (cb) {
  197. cb(msg.data);
  198. }
  199. else {
  200. var l = pm.data("listeners.postmessage") || {};
  201. var fns = l[msg.type] || [];
  202. for (var i=0,len=fns.length; i<len; i++) {
  203. var o = fns[i];
  204. if (o.origin && o.origin !== '*' && e.origin !== o.origin) {
  205. console.warn("postmessage message origin mismatch", e.origin, o.origin);
  206. if (msg.errback) {
  207. // notify post message errback
  208. var error = {
  209. message: "postmessage origin mismatch",
  210. origin: [e.origin, o.origin]
  211. };
  212. pm.send({target:e.source, data:error, type:msg.errback});
  213. }
  214. continue;
  215. }
  216. function sendReply ( data ) {
  217. if (msg.callback) {
  218. pm.send({target:e.source, data:data, type:msg.callback});
  219. }
  220. }
  221. try {
  222. if ( o.callback ) {
  223. o.fn(msg.data, sendReply, e);
  224. } else {
  225. sendReply ( o.fn(msg.data, e) );
  226. }
  227. }
  228. catch (ex) {
  229. if (msg.errback) {
  230. // notify post message errback
  231. pm.send({target:e.source, data:ex, type:msg.errback});
  232. } else {
  233. throw ex;
  234. }
  235. }
  236. };
  237. }
  238. }
  239. };
  240. // location hash polling
  241. pm.hash = {
  242. send: function(options, msg) {
  243. //console.log("hash.send", target_window, options, msg);
  244. var target_window = options.target,
  245. target_url = options.url;
  246. if (!target_url) {
  247. console.warn("postmessage target window url is required");
  248. return;
  249. }
  250. target_url = pm.hash._url(target_url);
  251. var source_window,
  252. source_url = pm.hash._url(window.location.href);
  253. if (window == target_window.parent) {
  254. source_window = "parent";
  255. }
  256. else {
  257. try {
  258. for (var i=0,len=parent.frames.length; i<len; i++) {
  259. var f = parent.frames[i];
  260. if (f == window) {
  261. source_window = i;
  262. break;
  263. }
  264. };
  265. }
  266. catch(ex) {
  267. // Opera: security error trying to access parent.frames x-origin
  268. // juse use window.name
  269. source_window = window.name;
  270. }
  271. }
  272. if (source_window == null) {
  273. console.warn("postmessage windows must be direct parent/child windows and the child must be available through the parent window.frames list");
  274. return;
  275. }
  276. var hashmessage = {
  277. "x-requested-with": "postmessage",
  278. source: {
  279. name: source_window,
  280. url: source_url
  281. },
  282. postmessage: msg
  283. };
  284. var hash_id = "#x-postmessage-id=" + pm._random();
  285. target_window.location = target_url + hash_id + encodeURIComponent(JSON.stringify(hashmessage));
  286. },
  287. _regex: /^\#x\-postmessage\-id\=(\w{32})/,
  288. _regex_len: "#x-postmessage-id=".length + 32,
  289. _bind: function() {
  290. // are we already listening to message events on this w?
  291. if (!pm.data("polling.postmessage")) {
  292. setInterval(function() {
  293. var hash = "" + window.location.hash,
  294. m = pm.hash._regex.exec(hash);
  295. if (m) {
  296. var id = m[1];
  297. if (pm.hash._last !== id) {
  298. pm.hash._last = id;
  299. pm.hash._dispatch(hash.substring(pm.hash._regex_len));
  300. }
  301. }
  302. }, $.pm.poll || 200);
  303. pm.data("polling.postmessage", 1);
  304. }
  305. },
  306. _dispatch: function(hash) {
  307. if (!hash) {
  308. return;
  309. }
  310. try {
  311. hash = JSON.parse(decodeURIComponent(hash));
  312. if (!(hash['x-requested-with'] === 'postmessage' &&
  313. hash.source && hash.source.name != null && hash.source.url && hash.postmessage)) {
  314. // ignore since hash could've come from somewhere else
  315. return;
  316. }
  317. }
  318. catch (ex) {
  319. // ignore since hash could've come from somewhere else
  320. return;
  321. }
  322. var msg = hash.postmessage,
  323. cbs = pm.data("callbacks.postmessage") || {},
  324. cb = cbs[msg.type];
  325. if (cb) {
  326. cb(msg.data);
  327. }
  328. else {
  329. var source_window;
  330. if (hash.source.name === "parent") {
  331. source_window = window.parent;
  332. }
  333. else {
  334. source_window = window.frames[hash.source.name];
  335. }
  336. var l = pm.data("listeners.postmessage") || {};
  337. var fns = l[msg.type] || [];
  338. for (var i=0,len=fns.length; i<len; i++) {
  339. var o = fns[i];
  340. if (o.origin) {
  341. var origin = /https?\:\/\/[^\/]*/.exec(hash.source.url)[0];
  342. if (o.origin !== '*' && origin !== o.origin) {
  343. console.warn("postmessage message origin mismatch", origin, o.origin);
  344. if (msg.errback) {
  345. // notify post message errback
  346. var error = {
  347. message: "postmessage origin mismatch",
  348. origin: [origin, o.origin]
  349. };
  350. pm.send({target:source_window, data:error, type:msg.errback, hash:true, url:hash.source.url});
  351. }
  352. continue;
  353. }
  354. }
  355. function sendReply ( data ) {
  356. if (msg.callback) {
  357. pm.send({target:source_window, data:data, type:msg.callback, hash:true, url:hash.source.url});
  358. }
  359. }
  360. try {
  361. if ( o.callback ) {
  362. o.fn(msg.data, sendReply);
  363. } else {
  364. sendReply ( o.fn(msg.data) );
  365. }
  366. }
  367. catch (ex) {
  368. if (msg.errback) {
  369. // notify post message errback
  370. pm.send({target:source_window, data:ex, type:msg.errback, hash:true, url:hash.source.url});
  371. } else {
  372. throw ex;
  373. }
  374. }
  375. };
  376. }
  377. },
  378. _url: function(url) {
  379. // url minus hash part
  380. return (""+url).replace(/#.*$/, "");
  381. }
  382. };
  383. $.extend(pm, {
  384. defaults: {
  385. target: null, /* target window (required) */
  386. url: null, /* target window url (required if no window.postMessage or hash == true) */
  387. type: null, /* message type (required) */
  388. data: null, /* message data (required) */
  389. success: null, /* success callback (optional) */
  390. error: null, /* error callback (optional) */
  391. origin: "*", /* postmessage origin (optional) */
  392. hash: false /* use location hash for message passing (optional) */
  393. }
  394. });
  395. })(this, typeof jQuery === "undefined" ? NO_JQUERY : jQuery);
  396. /**
  397. * http://www.JSON.org/json2.js
  398. **/
  399. if (! ("JSON" in window && window.JSON)){JSON={}}(function(){function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(key){return this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z"};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf()}}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==="string"){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function"){JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else{if(typeof space==="string"){indent=space}}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}}());