Path: blob/trunk/third_party/closure/goog/net/jsonp.js
2868 views
// Copyright 2006 The Closure Library Authors. All Rights Reserved.1//2// Licensed under the Apache License, Version 2.0 (the "License");3// you may not use this file except in compliance with the License.4// You may obtain a copy of the License at5//6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS-IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314// The original file lives here: http://go/cross_domain_channel.js1516/**17* @fileoverview Implements a cross-domain communication channel. A18* typical web page is prevented by browser security from sending19* request, such as a XMLHttpRequest, to other servers than the ones20* from which it came. The Jsonp class provides a workaround by21* using dynamically generated script tags. Typical usage:.22*23* var jsonp = new goog.net.Jsonp(new goog.Uri('http://my.host.com/servlet'));24* var payload = { 'foo': 1, 'bar': true };25* jsonp.send(payload, function(reply) { alert(reply) });26*27* This script works in all browsers that are currently supported by28* the Google Maps API, which is IE 6.0+, Firefox 0.8+, Safari 1.2.4+,29* Netscape 7.1+, Mozilla 1.4+, Opera 8.02+.30*31*/3233goog.provide('goog.net.Jsonp');3435goog.require('goog.Uri');36goog.require('goog.net.jsloader');3738// WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING39//40// This class allows us (Google) to send data from non-Google and thus41// UNTRUSTED pages to our servers. Under NO CIRCUMSTANCES return42// anything sensitive, such as session or cookie specific data. Return43// only data that you want parties external to Google to have. Also44// NEVER use this method to send data from web pages to untrusted45// servers, or redirects to unknown servers (www.google.com/cache,46// /q=xx&btnl, /url, www.googlepages.com, etc.)47//48// WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING49505152/**53* Creates a new cross domain channel that sends data to the specified54* host URL. By default, if no reply arrives within 5s, the channel55* assumes the call failed to complete successfully.56*57* @param {goog.Uri|string} uri The Uri of the server side code that receives58* data posted through this channel (e.g.,59* "http://maps.google.com/maps/geo").60*61* @param {string=} opt_callbackParamName The parameter name that is used to62* specify the callback. Defaults to "callback".63*64* @constructor65* @final66*/67goog.net.Jsonp = function(uri, opt_callbackParamName) {68/**69* The uri_ object will be used to encode the payload that is sent to the70* server.71* @type {goog.Uri}72* @private73*/74this.uri_ = new goog.Uri(uri);7576/**77* This is the callback parameter name that is added to the uri.78* @type {string}79* @private80*/81this.callbackParamName_ =82opt_callbackParamName ? opt_callbackParamName : 'callback';8384/**85* The length of time, in milliseconds, this channel is prepared86* to wait for for a request to complete. The default value is 5 seconds.87* @type {number}88* @private89*/90this.timeout_ = 5000;9192/**93* The nonce to use in the dynamically generated script tags. This is used for94* allowing the script callbacks to execute when the page has an enforced95* Content Security Policy.96* @type {string}97* @private98*/99this.nonce_ = '';100};101102103/**104* The prefix for the callback name which will be stored on goog.global.105*/106goog.net.Jsonp.CALLBACKS = '_callbacks_';107108109/**110* Used to generate unique callback IDs. The counter must be global because111* all channels share a common callback object.112* @private113*/114goog.net.Jsonp.scriptCounter_ = 0;115116117/**118* Static private method which returns the global unique callback id.119*120* @param {string} id The id of the script node.121* @return {string} A global unique id used to store callback on goog.global122* object.123* @private124*/125goog.net.Jsonp.getCallbackId_ = function(id) {126return goog.net.Jsonp.CALLBACKS + '__' + id;127};128129130/**131* Sets the length of time, in milliseconds, this channel is prepared132* to wait for for a request to complete. If the call is not competed133* within the set time span, it is assumed to have failed. To wait134* indefinitely for a request to complete set the timout to a negative135* number.136*137* @param {number} timeout The length of time before calls are138* interrupted.139*/140goog.net.Jsonp.prototype.setRequestTimeout = function(timeout) {141this.timeout_ = timeout;142};143144145/**146* Returns the current timeout value, in milliseconds.147*148* @return {number} The timeout value.149*/150goog.net.Jsonp.prototype.getRequestTimeout = function() {151return this.timeout_;152};153154155/**156* Sets the nonce value for CSP. This nonce value will be added to any created157* script elements and must match the nonce provided in the158* Content-Security-Policy header sent by the server for the callback to pass159* CSP enforcement.160*161* @param {string} nonce The CSP nonce value.162*/163goog.net.Jsonp.prototype.setNonce = function(nonce) {164this.nonce_ = nonce;165};166167168/**169* Sends the given payload to the URL specified at the construction170* time. The reply is delivered to the given replyCallback. If the171* errorCallback is specified and the reply does not arrive within the172* timeout period set on this channel, the errorCallback is invoked173* with the original payload.174*175* If no reply callback is specified, then the response is expected to176* consist of calls to globally registered functions. No &callback=177* URL parameter will be sent in the request, and the script element178* will be cleaned up after the timeout.179*180* @param {Object=} opt_payload Name-value pairs. If given, these will be181* added as parameters to the supplied URI as GET parameters to the182* given server URI.183*184* @param {Function=} opt_replyCallback A function expecting one185* argument, called when the reply arrives, with the response data.186*187* @param {Function=} opt_errorCallback A function expecting one188* argument, called on timeout, with the payload (if given), otherwise189* null.190*191* @param {string=} opt_callbackParamValue Value to be used as the192* parameter value for the callback parameter (callbackParamName).193* To be used when the value needs to be fixed by the client for a194* particular request, to make use of the cached responses for the request.195* NOTE: If multiple requests are made with the same196* opt_callbackParamValue, only the last call will work whenever the197* response comes back.198*199* @return {!Object} A request descriptor that may be used to cancel this200* transmission, or null, if the message may not be cancelled.201*/202goog.net.Jsonp.prototype.send = function(203opt_payload, opt_replyCallback, opt_errorCallback, opt_callbackParamValue) {204205var payload = opt_payload || null;206207var id = opt_callbackParamValue ||208'_' + (goog.net.Jsonp.scriptCounter_++).toString(36) +209goog.now().toString(36);210var callbackId = goog.net.Jsonp.getCallbackId_(id);211212// Create a new Uri object onto which this payload will be added213var uri = this.uri_.clone();214if (payload) {215goog.net.Jsonp.addPayloadToUri_(payload, uri);216}217218if (opt_replyCallback) {219var reply = goog.net.Jsonp.newReplyHandler_(id, opt_replyCallback);220// Register the callback on goog.global to make it discoverable221// by jsonp response.222goog.global[callbackId] = reply;223uri.setParameterValues(this.callbackParamName_, callbackId);224}225226var options = {timeout: this.timeout_, cleanupWhenDone: true};227if (this.nonce_) {228options.attributes = {'nonce': this.nonce_};229}230231var deferred = goog.net.jsloader.load(uri.toString(), options);232var error = goog.net.Jsonp.newErrorHandler_(id, payload, opt_errorCallback);233deferred.addErrback(error);234235return {id_: id, deferred_: deferred};236};237238239/**240* Cancels a given request. The request must be exactly the object returned by241* the send method.242*243* @param {Object} request The request object returned by the send method.244*/245goog.net.Jsonp.prototype.cancel = function(request) {246if (request) {247if (request.deferred_) {248request.deferred_.cancel();249}250if (request.id_) {251goog.net.Jsonp.cleanup_(request.id_, false);252}253}254};255256257/**258* Creates a timeout callback that calls the given timeoutCallback with the259* original payload.260*261* @param {string} id The id of the script node.262* @param {Object} payload The payload that was sent to the server.263* @param {Function=} opt_errorCallback The function called on timeout.264* @return {!Function} A zero argument function that handles callback duties.265* @private266*/267goog.net.Jsonp.newErrorHandler_ = function(id, payload, opt_errorCallback) {268/**269* When we call across domains with a request, this function is the270* timeout handler. Once it's done executing the user-specified271* error-handler, it removes the script node and original function.272*/273return function() {274goog.net.Jsonp.cleanup_(id, false);275if (opt_errorCallback) {276opt_errorCallback(payload);277}278};279};280281282/**283* Creates a reply callback that calls the given replyCallback with data284* returned by the server.285*286* @param {string} id The id of the script node.287* @param {Function} replyCallback The function called on reply.288* @return {!Function} A reply callback function.289* @private290*/291goog.net.Jsonp.newReplyHandler_ = function(id, replyCallback) {292/**293* This function is the handler for the all-is-well response. It294* clears the error timeout handler, calls the user's handler, then295* removes the script node and itself.296*297* @param {...Object} var_args The response data sent from the server.298*/299var handler = function(var_args) {300goog.net.Jsonp.cleanup_(id, true);301replyCallback.apply(undefined, arguments);302};303return handler;304};305306307/**308* Removes the reply handler registered on goog.global object.309*310* @param {string} id The id of the script node to be removed.311* @param {boolean} deleteReplyHandler If true, delete the reply handler312* instead of setting it to nullFunction (if we know the callback could313* never be called again).314* @private315*/316goog.net.Jsonp.cleanup_ = function(id, deleteReplyHandler) {317var callbackId = goog.net.Jsonp.getCallbackId_(id);318if (goog.global[callbackId]) {319if (deleteReplyHandler) {320try {321delete goog.global[callbackId];322} catch (e) {323// NOTE: Workaround to delete property on 'window' in IE <= 8, see:324// http://stackoverflow.com/questions/1073414/deleting-a-window-property-in-ie325goog.global[callbackId] = undefined;326}327} else {328// Removing the script tag doesn't necessarily prevent the script329// from firing, so we make the callback a noop.330goog.global[callbackId] = goog.nullFunction;331}332}333};334335336/**337* Returns URL encoded payload. The payload should be a map of name-value338* pairs, in the form {"foo": 1, "bar": true, ...}. If the map is empty,339* the URI will be unchanged.340*341* <p>The method uses hasOwnProperty() to assure the properties are on the342* object, not on its prototype.343*344* @param {!Object} payload A map of value name pairs to be encoded.345* A value may be specified as an array, in which case a query parameter346* will be created for each value, e.g.:347* {"foo": [1,2]} will encode to "foo=1&foo=2".348*349* @param {!goog.Uri} uri A Uri object onto which the payload key value pairs350* will be encoded.351*352* @return {!goog.Uri} A reference to the Uri sent as a parameter.353* @private354*/355goog.net.Jsonp.addPayloadToUri_ = function(payload, uri) {356for (var name in payload) {357// NOTE(user): Safari/1.3 doesn't have hasOwnProperty(). In that358// case, we iterate over all properties as a very lame workaround.359if (!payload.hasOwnProperty || payload.hasOwnProperty(name)) {360uri.setParameterValues(name, payload[name]);361}362}363return uri;364};365366367// WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING368//369// This class allows us (Google) to send data from non-Google and thus370// UNTRUSTED pages to our servers. Under NO CIRCUMSTANCES return371// anything sensitive, such as session or cookie specific data. Return372// only data that you want parties external to Google to have. Also373// NEVER use this method to send data from web pages to untrusted374// servers, or redirects to unknown servers (www.google.com/cache,375// /q=xx&btnl, /url, www.googlepages.com, etc.)376//377// WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING378379380