xip.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /*
  2. Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
  3. Available via Academic Free License >= 2.1 OR the modified BSD license.
  4. see: http://dojotoolkit.org/license for details
  5. */
  6. if(!dojo._hasResource["dojox.io.proxy.xip"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
  7. dojo._hasResource["dojox.io.proxy.xip"] = true;
  8. dojo.provide("dojox.io.proxy.xip");
  9. dojo.require("dojo.io.iframe");
  10. dojo.require("dojox.data.dom");
  11. dojox.io.proxy.xip = {
  12. //summary: Object that implements the iframe handling for XMLHttpRequest
  13. //IFrame Proxying.
  14. //description: Do not use this object directly. See the Dojo Book page
  15. //on XMLHttpRequest IFrame Proxying:
  16. //http://dojotoolkit.org/book/dojo-book-0-4/part-5-connecting-pieces/i-o/cross-domain-xmlhttprequest-using-iframe-proxy
  17. //Usage of XHR IFrame Proxying does not work from local disk in Safari.
  18. /*
  19. This code is really focused on just sending one complete request to the server, and
  20. receiving one complete response per iframe. The code does not expect to reuse iframes for multiple XHR request/response
  21. sequences. This might be reworked later if performance indicates a need for it.
  22. xip fragment identifier/hash values have the form:
  23. #id:cmd:realEncodedMessage
  24. id: some ID that should be unique among message fragments. No inherent meaning,
  25. just something to make sure the hash value is unique so the message
  26. receiver knows a new message is available.
  27. cmd: command to the receiver. Valid values are:
  28. - init: message used to init the frame. Sent as the first URL when loading
  29. the page. Contains some config parameters.
  30. - loaded: the remote frame is loaded. Only sent from xip_client.html to this module.
  31. - ok: the message that this page sent was received OK. The next message may
  32. now be sent.
  33. - start: the start message of a block of messages (a complete message may
  34. need to be segmented into many messages to get around the limitiations
  35. of the size of an URL that a browser accepts.
  36. - part: indicates this is a part of a message.
  37. - end: the end message of a block of messages. The message can now be acted upon.
  38. If the message is small enough that it doesn't need to be segmented, then
  39. just one hash value message can be sent with "end" as the command.
  40. To reassemble a segmented message, the realEncodedMessage parts just have to be concatenated
  41. together.
  42. */
  43. xipClientUrl: ((dojo.config || djConfig)["xipClientUrl"]) || dojo.moduleUrl("dojox.io.proxy", "xip_client.html"),
  44. //MSIE has the lowest limit for URLs with fragment identifiers,
  45. //at around 4K. Choosing a slightly smaller number for good measure.
  46. urlLimit: 4000,
  47. _callbackName: (dojox._scopeName || "dojox") + ".io.proxy.xip.fragmentReceived",
  48. _state: {},
  49. _stateIdCounter: 0,
  50. _isWebKit: navigator.userAgent.indexOf("WebKit") != -1,
  51. send: function(/*Object*/facade){
  52. //summary: starts the xdomain request using the provided facade.
  53. //This method first does some init work, then delegates to _realSend.
  54. var url = this.xipClientUrl;
  55. //Make sure we are not dealing with javascript urls, just to be safe.
  56. if(url.split(":")[0].match(/javascript/i) || facade._ifpServerUrl.split(":")[0].match(/javascript/i)){
  57. return;
  58. }
  59. //Make xip_client a full URL.
  60. var colonIndex = url.indexOf(":");
  61. var slashIndex = url.indexOf("/");
  62. if(colonIndex == -1 || slashIndex < colonIndex){
  63. //No colon or we are starting with a / before a colon, so we need to make a full URL.
  64. var loc = window.location.href;
  65. if(slashIndex == 0){
  66. //Have a full path, just need the domain.
  67. url = loc.substring(0, loc.indexOf("/", 9)) + url; //Using 9 to get past http(s)://
  68. }else{
  69. url = loc.substring(0, (loc.lastIndexOf("/") + 1)) + url;
  70. }
  71. }
  72. this.fullXipClientUrl = url;
  73. //Set up an HTML5 messaging listener if postMessage exists.
  74. //As of this writing, this is only useful to get Opera 9.25+ to work.
  75. if(typeof document.postMessage != "undefined"){
  76. document.addEventListener("message", dojo.hitch(this, this.fragmentReceivedEvent), false);
  77. }
  78. //Now that we did first time init, always use the realSend method.
  79. this.send = this._realSend;
  80. return this._realSend(facade); //Object
  81. },
  82. _realSend: function(facade){
  83. //summary: starts the actual xdomain request using the provided facade.
  84. var stateId = "XhrIframeProxy" + (this._stateIdCounter++);
  85. facade._stateId = stateId;
  86. var frameUrl = facade._ifpServerUrl + "#0:init:id=" + stateId + "&client="
  87. + encodeURIComponent(this.fullXipClientUrl) + "&callback=" + encodeURIComponent(this._callbackName);
  88. this._state[stateId] = {
  89. facade: facade,
  90. stateId: stateId,
  91. clientFrame: dojo.io.iframe.create(stateId, "", frameUrl),
  92. isSending: false,
  93. serverUrl: facade._ifpServerUrl,
  94. requestData: null,
  95. responseMessage: "",
  96. requestParts: [],
  97. idCounter: 1,
  98. partIndex: 0,
  99. serverWindow: null
  100. };
  101. return stateId; //Object
  102. },
  103. receive: function(/*String*/stateId, /*String*/urlEncodedData){
  104. /* urlEncodedData should have the following params:
  105. - responseHeaders
  106. - status
  107. - statusText
  108. - responseText
  109. */
  110. //Decode response data.
  111. var response = {};
  112. var nvPairs = urlEncodedData.split("&");
  113. for(var i = 0; i < nvPairs.length; i++){
  114. if(nvPairs[i]){
  115. var nameValue = nvPairs[i].split("=");
  116. response[decodeURIComponent(nameValue[0])] = decodeURIComponent(nameValue[1]);
  117. }
  118. }
  119. //Set data on facade object.
  120. var state = this._state[stateId];
  121. var facade = state.facade;
  122. facade._setResponseHeaders(response.responseHeaders);
  123. if(response.status == 0 || response.status){
  124. facade.status = parseInt(response.status, 10);
  125. }
  126. if(response.statusText){
  127. facade.statusText = response.statusText;
  128. }
  129. if(response.responseText){
  130. facade.responseText = response.responseText;
  131. //Fix responseXML.
  132. var contentType = facade.getResponseHeader("Content-Type");
  133. if(contentType){
  134. var mimeType = contentType.split(";")[0];
  135. if(mimeType.indexOf("application/xml") == 0 || mimeType.indexOf("text/xml") == 0){
  136. facade.responseXML = dojox.data.dom.createDocument(response.responseText, contentType);
  137. }
  138. }
  139. }
  140. facade.readyState = 4;
  141. this.destroyState(stateId);
  142. },
  143. frameLoaded: function(/*String*/stateId){
  144. var state = this._state[stateId];
  145. var facade = state.facade;
  146. var reqHeaders = [];
  147. for(var param in facade._requestHeaders){
  148. reqHeaders.push(param + ": " + facade._requestHeaders[param]);
  149. }
  150. var requestData = {
  151. uri: facade._uri
  152. };
  153. if(reqHeaders.length > 0){
  154. requestData.requestHeaders = reqHeaders.join("\r\n");
  155. }
  156. if(facade._method){
  157. requestData.method = facade._method;
  158. }
  159. if(facade._bodyData){
  160. requestData.data = facade._bodyData;
  161. }
  162. this.sendRequest(stateId, dojo.objectToQuery(requestData));
  163. },
  164. destroyState: function(/*String*/stateId){
  165. var state = this._state[stateId];
  166. if(state){
  167. delete this._state[stateId];
  168. var parentNode = state.clientFrame.parentNode;
  169. parentNode.removeChild(state.clientFrame);
  170. state.clientFrame = null;
  171. state = null;
  172. }
  173. },
  174. createFacade: function(){
  175. if(arguments && arguments[0] && arguments[0].iframeProxyUrl){
  176. return new dojox.io.proxy.xip.XhrIframeFacade(arguments[0].iframeProxyUrl);
  177. }else{
  178. return dojox.io.proxy.xip._xhrObjOld.apply(dojo, arguments);
  179. }
  180. },
  181. //**** State-bound methods ****
  182. sendRequest: function(stateId, encodedData){
  183. var state = this._state[stateId];
  184. if(!state.isSending){
  185. state.isSending = true;
  186. state.requestData = encodedData || "";
  187. //Get a handle to the server iframe.
  188. state.serverWindow = frames[state.stateId];
  189. if (!state.serverWindow){
  190. state.serverWindow = document.getElementById(state.stateId).contentWindow;
  191. }
  192. //Make sure we have contentWindow, but only do this for non-postMessage
  193. //browsers (right now just opera is postMessage).
  194. if(typeof document.postMessage == "undefined"){
  195. if(state.serverWindow.contentWindow){
  196. state.serverWindow = state.serverWindow.contentWindow;
  197. }
  198. }
  199. this.sendRequestStart(stateId);
  200. }
  201. },
  202. sendRequestStart: function(stateId){
  203. //Break the message into parts, if necessary.
  204. var state = this._state[stateId];
  205. state.requestParts = [];
  206. var reqData = state.requestData;
  207. var urlLength = state.serverUrl.length;
  208. var partLength = this.urlLimit - urlLength;
  209. var reqIndex = 0;
  210. while((reqData.length - reqIndex) + urlLength > this.urlLimit){
  211. var part = reqData.substring(reqIndex, reqIndex + partLength);
  212. //Safari will do some extra hex escaping unless we keep the original hex
  213. //escaping complete.
  214. var percentIndex = part.lastIndexOf("%");
  215. if(percentIndex == part.length - 1 || percentIndex == part.length - 2){
  216. part = part.substring(0, percentIndex);
  217. }
  218. state.requestParts.push(part);
  219. reqIndex += part.length;
  220. }
  221. state.requestParts.push(reqData.substring(reqIndex, reqData.length));
  222. state.partIndex = 0;
  223. this.sendRequestPart(stateId);
  224. },
  225. sendRequestPart: function(stateId){
  226. var state = this._state[stateId];
  227. if(state.partIndex < state.requestParts.length){
  228. //Get the message part.
  229. var partData = state.requestParts[state.partIndex];
  230. //Get the command.
  231. var cmd = "part";
  232. if(state.partIndex + 1 == state.requestParts.length){
  233. cmd = "end";
  234. }else if (state.partIndex == 0){
  235. cmd = "start";
  236. }
  237. this.setServerUrl(stateId, cmd, partData);
  238. state.partIndex++;
  239. }
  240. },
  241. setServerUrl: function(stateId, cmd, message){
  242. var serverUrl = this.makeServerUrl(stateId, cmd, message);
  243. var state = this._state[stateId];
  244. //Safari won't let us replace across domains.
  245. if(this._isWebKit){
  246. state.serverWindow.location = serverUrl;
  247. }else{
  248. state.serverWindow.location.replace(serverUrl);
  249. }
  250. },
  251. makeServerUrl: function(stateId, cmd, message){
  252. var state = this._state[stateId];
  253. var serverUrl = state.serverUrl + "#" + (state.idCounter++) + ":" + cmd;
  254. if(message){
  255. serverUrl += ":" + message;
  256. }
  257. return serverUrl;
  258. },
  259. fragmentReceivedEvent: function(evt){
  260. //summary: HTML5 document messaging endpoint. Unpack the event to see
  261. //if we want to use it.
  262. if(evt.uri.split("#")[0] == this.fullXipClientUrl){
  263. this.fragmentReceived(evt.data);
  264. }
  265. },
  266. fragmentReceived: function(frag){
  267. var index = frag.indexOf("#");
  268. var stateId = frag.substring(0, index);
  269. var encodedData = frag.substring(index + 1, frag.length);
  270. var msg = this.unpackMessage(encodedData);
  271. var state = this._state[stateId];
  272. switch(msg.command){
  273. case "loaded":
  274. this.frameLoaded(stateId);
  275. break;
  276. case "ok":
  277. this.sendRequestPart(stateId);
  278. break;
  279. case "start":
  280. state.responseMessage = "" + msg.message;
  281. this.setServerUrl(stateId, "ok");
  282. break;
  283. case "part":
  284. state.responseMessage += msg.message;
  285. this.setServerUrl(stateId, "ok");
  286. break;
  287. case "end":
  288. this.setServerUrl(stateId, "ok");
  289. state.responseMessage += msg.message;
  290. this.receive(stateId, state.responseMessage);
  291. break;
  292. }
  293. },
  294. unpackMessage: function(encodedMessage){
  295. var parts = encodedMessage.split(":");
  296. var command = parts[1];
  297. encodedMessage = parts[2] || "";
  298. var config = null;
  299. if(command == "init"){
  300. var configParts = encodedMessage.split("&");
  301. config = {};
  302. for(var i = 0; i < configParts.length; i++){
  303. var nameValue = configParts[i].split("=");
  304. config[decodeURIComponent(nameValue[0])] = decodeURIComponent(nameValue[1]);
  305. }
  306. }
  307. return {command: command, message: encodedMessage, config: config};
  308. }
  309. }
  310. //Replace the normal XHR factory with the proxy one.
  311. dojox.io.proxy.xip._xhrObjOld = dojo._xhrObj;
  312. dojo._xhrObj = dojox.io.proxy.xip.createFacade;
  313. /**
  314. Using this a reference: http://www.w3.org/TR/XMLHttpRequest/
  315. Does not implement the onreadystate callback since dojo.xhr* does
  316. not use it.
  317. */
  318. dojox.io.proxy.xip.XhrIframeFacade = function(ifpServerUrl){
  319. //summary: XMLHttpRequest facade object used by dojox.io.proxy.xip.
  320. //description: Do not use this object directly. See the Dojo Book page
  321. //on XMLHttpRequest IFrame Proxying:
  322. //http://dojotoolkit.org/book/dojo-book-0-4/part-5-connecting-pieces/i-o/cross-domain-xmlhttprequest-using-iframe-proxy
  323. this._requestHeaders = {};
  324. this._allResponseHeaders = null;
  325. this._responseHeaders = {};
  326. this._method = null;
  327. this._uri = null;
  328. this._bodyData = null;
  329. this.responseText = null;
  330. this.responseXML = null;
  331. this.status = null;
  332. this.statusText = null;
  333. this.readyState = 0;
  334. this._ifpServerUrl = ifpServerUrl;
  335. this._stateId = null;
  336. }
  337. dojo.extend(dojox.io.proxy.xip.XhrIframeFacade, {
  338. //The open method does not properly reset since Dojo does not reuse XHR objects.
  339. open: function(/*String*/method, /*String*/uri){
  340. this._method = method;
  341. this._uri = uri;
  342. this.readyState = 1;
  343. },
  344. setRequestHeader: function(/*String*/header, /*String*/value){
  345. this._requestHeaders[header] = value;
  346. },
  347. send: function(/*String*/stringData){
  348. this._bodyData = stringData;
  349. this._stateId = dojox.io.proxy.xip.send(this);
  350. this.readyState = 2;
  351. },
  352. abort: function(){
  353. dojox.io.proxy.xip.destroyState(this._stateId);
  354. },
  355. getAllResponseHeaders: function(){
  356. return this._allResponseHeaders; //String
  357. },
  358. getResponseHeader: function(/*String*/header){
  359. return this._responseHeaders[header]; //String
  360. },
  361. _setResponseHeaders: function(/*String*/allHeaders){
  362. if(allHeaders){
  363. this._allResponseHeaders = allHeaders;
  364. //Make sure ther are now CR characters in the headers.
  365. allHeaders = allHeaders.replace(/\r/g, "");
  366. var nvPairs = allHeaders.split("\n");
  367. for(var i = 0; i < nvPairs.length; i++){
  368. if(nvPairs[i]){
  369. var nameValue = nvPairs[i].split(": ");
  370. this._responseHeaders[nameValue[0]] = nameValue[1];
  371. }
  372. }
  373. }
  374. }
  375. });
  376. }