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