jsonp.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // The original file lives here: http://go/cross_domain_channel.js
  15. /**
  16. * @fileoverview Implements a cross-domain communication channel. A
  17. * typical web page is prevented by browser security from sending
  18. * request, such as a XMLHttpRequest, to other servers than the ones
  19. * from which it came. The Jsonp class provides a workaround by
  20. * using dynamically generated script tags. Typical usage:.
  21. *
  22. * var jsonp = new goog.net.Jsonp(new goog.Uri('http://my.host.com/servlet'));
  23. * var payload = { 'foo': 1, 'bar': true };
  24. * jsonp.send(payload, function(reply) { alert(reply) });
  25. *
  26. * This script works in all browsers that are currently supported by
  27. * the Google Maps API, which is IE 6.0+, Firefox 0.8+, Safari 1.2.4+,
  28. * Netscape 7.1+, Mozilla 1.4+, Opera 8.02+.
  29. *
  30. */
  31. goog.provide('goog.net.Jsonp');
  32. goog.require('goog.Uri');
  33. goog.require('goog.net.jsloader');
  34. // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
  35. //
  36. // This class allows us (Google) to send data from non-Google and thus
  37. // UNTRUSTED pages to our servers. Under NO CIRCUMSTANCES return
  38. // anything sensitive, such as session or cookie specific data. Return
  39. // only data that you want parties external to Google to have. Also
  40. // NEVER use this method to send data from web pages to untrusted
  41. // servers, or redirects to unknown servers (www.google.com/cache,
  42. // /q=xx&btnl, /url, www.googlepages.com, etc.)
  43. //
  44. // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
  45. /**
  46. * Creates a new cross domain channel that sends data to the specified
  47. * host URL. By default, if no reply arrives within 5s, the channel
  48. * assumes the call failed to complete successfully.
  49. *
  50. * @param {goog.Uri|string} uri The Uri of the server side code that receives
  51. * data posted through this channel (e.g.,
  52. * "http://maps.google.com/maps/geo").
  53. *
  54. * @param {string=} opt_callbackParamName The parameter name that is used to
  55. * specify the callback. Defaults to "callback".
  56. *
  57. * @constructor
  58. * @final
  59. */
  60. goog.net.Jsonp = function(uri, opt_callbackParamName) {
  61. /**
  62. * The uri_ object will be used to encode the payload that is sent to the
  63. * server.
  64. * @type {goog.Uri}
  65. * @private
  66. */
  67. this.uri_ = new goog.Uri(uri);
  68. /**
  69. * This is the callback parameter name that is added to the uri.
  70. * @type {string}
  71. * @private
  72. */
  73. this.callbackParamName_ =
  74. opt_callbackParamName ? opt_callbackParamName : 'callback';
  75. /**
  76. * The length of time, in milliseconds, this channel is prepared
  77. * to wait for for a request to complete. The default value is 5 seconds.
  78. * @type {number}
  79. * @private
  80. */
  81. this.timeout_ = 5000;
  82. /**
  83. * The nonce to use in the dynamically generated script tags. This is used for
  84. * allowing the script callbacks to execute when the page has an enforced
  85. * Content Security Policy.
  86. * @type {string}
  87. * @private
  88. */
  89. this.nonce_ = '';
  90. };
  91. /**
  92. * The prefix for the callback name which will be stored on goog.global.
  93. */
  94. goog.net.Jsonp.CALLBACKS = '_callbacks_';
  95. /**
  96. * Used to generate unique callback IDs. The counter must be global because
  97. * all channels share a common callback object.
  98. * @private
  99. */
  100. goog.net.Jsonp.scriptCounter_ = 0;
  101. /**
  102. * Static private method which returns the global unique callback id.
  103. *
  104. * @param {string} id The id of the script node.
  105. * @return {string} A global unique id used to store callback on goog.global
  106. * object.
  107. * @private
  108. */
  109. goog.net.Jsonp.getCallbackId_ = function(id) {
  110. return goog.net.Jsonp.CALLBACKS + '__' + id;
  111. };
  112. /**
  113. * Sets the length of time, in milliseconds, this channel is prepared
  114. * to wait for for a request to complete. If the call is not competed
  115. * within the set time span, it is assumed to have failed. To wait
  116. * indefinitely for a request to complete set the timout to a negative
  117. * number.
  118. *
  119. * @param {number} timeout The length of time before calls are
  120. * interrupted.
  121. */
  122. goog.net.Jsonp.prototype.setRequestTimeout = function(timeout) {
  123. this.timeout_ = timeout;
  124. };
  125. /**
  126. * Returns the current timeout value, in milliseconds.
  127. *
  128. * @return {number} The timeout value.
  129. */
  130. goog.net.Jsonp.prototype.getRequestTimeout = function() {
  131. return this.timeout_;
  132. };
  133. /**
  134. * Sets the nonce value for CSP. This nonce value will be added to any created
  135. * script elements and must match the nonce provided in the
  136. * Content-Security-Policy header sent by the server for the callback to pass
  137. * CSP enforcement.
  138. *
  139. * @param {string} nonce The CSP nonce value.
  140. */
  141. goog.net.Jsonp.prototype.setNonce = function(nonce) {
  142. this.nonce_ = nonce;
  143. };
  144. /**
  145. * Sends the given payload to the URL specified at the construction
  146. * time. The reply is delivered to the given replyCallback. If the
  147. * errorCallback is specified and the reply does not arrive within the
  148. * timeout period set on this channel, the errorCallback is invoked
  149. * with the original payload.
  150. *
  151. * If no reply callback is specified, then the response is expected to
  152. * consist of calls to globally registered functions. No &callback=
  153. * URL parameter will be sent in the request, and the script element
  154. * will be cleaned up after the timeout.
  155. *
  156. * @param {Object=} opt_payload Name-value pairs. If given, these will be
  157. * added as parameters to the supplied URI as GET parameters to the
  158. * given server URI.
  159. *
  160. * @param {Function=} opt_replyCallback A function expecting one
  161. * argument, called when the reply arrives, with the response data.
  162. *
  163. * @param {Function=} opt_errorCallback A function expecting one
  164. * argument, called on timeout, with the payload (if given), otherwise
  165. * null.
  166. *
  167. * @param {string=} opt_callbackParamValue Value to be used as the
  168. * parameter value for the callback parameter (callbackParamName).
  169. * To be used when the value needs to be fixed by the client for a
  170. * particular request, to make use of the cached responses for the request.
  171. * NOTE: If multiple requests are made with the same
  172. * opt_callbackParamValue, only the last call will work whenever the
  173. * response comes back.
  174. *
  175. * @return {!Object} A request descriptor that may be used to cancel this
  176. * transmission, or null, if the message may not be cancelled.
  177. */
  178. goog.net.Jsonp.prototype.send = function(
  179. opt_payload, opt_replyCallback, opt_errorCallback, opt_callbackParamValue) {
  180. var payload = opt_payload || null;
  181. var id = opt_callbackParamValue ||
  182. '_' + (goog.net.Jsonp.scriptCounter_++).toString(36) +
  183. goog.now().toString(36);
  184. var callbackId = goog.net.Jsonp.getCallbackId_(id);
  185. // Create a new Uri object onto which this payload will be added
  186. var uri = this.uri_.clone();
  187. if (payload) {
  188. goog.net.Jsonp.addPayloadToUri_(payload, uri);
  189. }
  190. if (opt_replyCallback) {
  191. var reply = goog.net.Jsonp.newReplyHandler_(id, opt_replyCallback);
  192. // Register the callback on goog.global to make it discoverable
  193. // by jsonp response.
  194. goog.global[callbackId] = reply;
  195. uri.setParameterValues(this.callbackParamName_, callbackId);
  196. }
  197. var options = {timeout: this.timeout_, cleanupWhenDone: true};
  198. if (this.nonce_) {
  199. options.attributes = {'nonce': this.nonce_};
  200. }
  201. var deferred = goog.net.jsloader.load(uri.toString(), options);
  202. var error = goog.net.Jsonp.newErrorHandler_(id, payload, opt_errorCallback);
  203. deferred.addErrback(error);
  204. return {id_: id, deferred_: deferred};
  205. };
  206. /**
  207. * Cancels a given request. The request must be exactly the object returned by
  208. * the send method.
  209. *
  210. * @param {Object} request The request object returned by the send method.
  211. */
  212. goog.net.Jsonp.prototype.cancel = function(request) {
  213. if (request) {
  214. if (request.deferred_) {
  215. request.deferred_.cancel();
  216. }
  217. if (request.id_) {
  218. goog.net.Jsonp.cleanup_(request.id_, false);
  219. }
  220. }
  221. };
  222. /**
  223. * Creates a timeout callback that calls the given timeoutCallback with the
  224. * original payload.
  225. *
  226. * @param {string} id The id of the script node.
  227. * @param {Object} payload The payload that was sent to the server.
  228. * @param {Function=} opt_errorCallback The function called on timeout.
  229. * @return {!Function} A zero argument function that handles callback duties.
  230. * @private
  231. */
  232. goog.net.Jsonp.newErrorHandler_ = function(id, payload, opt_errorCallback) {
  233. /**
  234. * When we call across domains with a request, this function is the
  235. * timeout handler. Once it's done executing the user-specified
  236. * error-handler, it removes the script node and original function.
  237. */
  238. return function() {
  239. goog.net.Jsonp.cleanup_(id, false);
  240. if (opt_errorCallback) {
  241. opt_errorCallback(payload);
  242. }
  243. };
  244. };
  245. /**
  246. * Creates a reply callback that calls the given replyCallback with data
  247. * returned by the server.
  248. *
  249. * @param {string} id The id of the script node.
  250. * @param {Function} replyCallback The function called on reply.
  251. * @return {!Function} A reply callback function.
  252. * @private
  253. */
  254. goog.net.Jsonp.newReplyHandler_ = function(id, replyCallback) {
  255. /**
  256. * This function is the handler for the all-is-well response. It
  257. * clears the error timeout handler, calls the user's handler, then
  258. * removes the script node and itself.
  259. *
  260. * @param {...Object} var_args The response data sent from the server.
  261. */
  262. var handler = function(var_args) {
  263. goog.net.Jsonp.cleanup_(id, true);
  264. replyCallback.apply(undefined, arguments);
  265. };
  266. return handler;
  267. };
  268. /**
  269. * Removes the reply handler registered on goog.global object.
  270. *
  271. * @param {string} id The id of the script node to be removed.
  272. * @param {boolean} deleteReplyHandler If true, delete the reply handler
  273. * instead of setting it to nullFunction (if we know the callback could
  274. * never be called again).
  275. * @private
  276. */
  277. goog.net.Jsonp.cleanup_ = function(id, deleteReplyHandler) {
  278. var callbackId = goog.net.Jsonp.getCallbackId_(id);
  279. if (goog.global[callbackId]) {
  280. if (deleteReplyHandler) {
  281. try {
  282. delete goog.global[callbackId];
  283. } catch (e) {
  284. // NOTE: Workaround to delete property on 'window' in IE <= 8, see:
  285. // http://stackoverflow.com/questions/1073414/deleting-a-window-property-in-ie
  286. goog.global[callbackId] = undefined;
  287. }
  288. } else {
  289. // Removing the script tag doesn't necessarily prevent the script
  290. // from firing, so we make the callback a noop.
  291. goog.global[callbackId] = goog.nullFunction;
  292. }
  293. }
  294. };
  295. /**
  296. * Returns URL encoded payload. The payload should be a map of name-value
  297. * pairs, in the form {"foo": 1, "bar": true, ...}. If the map is empty,
  298. * the URI will be unchanged.
  299. *
  300. * <p>The method uses hasOwnProperty() to assure the properties are on the
  301. * object, not on its prototype.
  302. *
  303. * @param {!Object} payload A map of value name pairs to be encoded.
  304. * A value may be specified as an array, in which case a query parameter
  305. * will be created for each value, e.g.:
  306. * {"foo": [1,2]} will encode to "foo=1&foo=2".
  307. *
  308. * @param {!goog.Uri} uri A Uri object onto which the payload key value pairs
  309. * will be encoded.
  310. *
  311. * @return {!goog.Uri} A reference to the Uri sent as a parameter.
  312. * @private
  313. */
  314. goog.net.Jsonp.addPayloadToUri_ = function(payload, uri) {
  315. for (var name in payload) {
  316. // NOTE(user): Safari/1.3 doesn't have hasOwnProperty(). In that
  317. // case, we iterate over all properties as a very lame workaround.
  318. if (!payload.hasOwnProperty || payload.hasOwnProperty(name)) {
  319. uri.setParameterValues(name, payload[name]);
  320. }
  321. }
  322. return uri;
  323. };
  324. // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
  325. //
  326. // This class allows us (Google) to send data from non-Google and thus
  327. // UNTRUSTED pages to our servers. Under NO CIRCUMSTANCES return
  328. // anything sensitive, such as session or cookie specific data. Return
  329. // only data that you want parties external to Google to have. Also
  330. // NEVER use this method to send data from web pages to untrusted
  331. // servers, or redirects to unknown servers (www.google.com/cache,
  332. // /q=xx&btnl, /url, www.googlepages.com, etc.)
  333. //
  334. // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING