| 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 |
/** |
| 16 |
* @fileoverview Wrapper class for handling XmlHttpRequests. |
| 17 |
* |
| 18 |
* One off requests can be sent through goog.net.XhrIo.send() or an |
| 19 |
* instance can be created to send multiple requests. Each request uses its |
| 20 |
* own XmlHttpRequest object and handles clearing of the event callback to |
| 21 |
* ensure no leaks. |
| 22 |
* |
| 23 |
* XhrIo is event based, it dispatches events on success, failure, finishing, |
| 24 |
* ready-state change, or progress (download and upload). |
| 25 |
* |
| 26 |
* The ready-state or timeout event fires first, followed by |
| 27 |
* a generic completed event. Then the abort, error, or success event |
| 28 |
* is fired as appropriate. Progress events are fired as they are |
| 29 |
* received. Lastly, the ready event will fire to indicate that the |
| 30 |
* object may be used to make another request. |
| 31 |
* |
| 32 |
* The error event may also be called before completed and |
| 33 |
* ready-state-change if the XmlHttpRequest.open() or .send() methods throw. |
| 34 |
* |
| 35 |
* This class does not support multiple requests, queuing, or prioritization. |
| 36 |
* |
| 37 |
* When progress events are supported by the browser, and progress is |
| 38 |
* enabled via .setProgressEventsEnabled(true), the |
| 39 |
* goog.net.EventType.PROGRESS event will be the re-dispatched browser |
| 40 |
* progress event. Additionally, a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event |
| 41 |
* will be fired for download and upload progress respectively. |
| 42 |
* |
| 43 |
*/ |
| 44 |
|
| 45 |
|
| 46 |
goog.provide('goog.net.XhrIo'); |
| 47 |
goog.provide('goog.net.XhrIo.ResponseType'); |
| 48 |
|
| 49 |
goog.require('goog.Timer'); |
| 50 |
goog.require('goog.array'); |
| 51 |
goog.require('goog.asserts'); |
| 52 |
goog.require('goog.debug.entryPointRegistry'); |
| 53 |
goog.require('goog.events.EventTarget'); |
| 54 |
goog.require('goog.json.hybrid'); |
| 55 |
goog.require('goog.log'); |
| 56 |
goog.require('goog.net.ErrorCode'); |
| 57 |
goog.require('goog.net.EventType'); |
| 58 |
goog.require('goog.net.HttpStatus'); |
| 59 |
goog.require('goog.net.XmlHttp'); |
| 60 |
goog.require('goog.string'); |
| 61 |
goog.require('goog.structs'); |
| 62 |
goog.require('goog.structs.Map'); |
| 63 |
goog.require('goog.uri.utils'); |
| 64 |
goog.require('goog.userAgent'); |
| 65 |
|
| 66 |
goog.forwardDeclare('goog.Uri'); |
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
/** |
| 71 |
* Basic class for handling XMLHttpRequests. |
| 72 |
* @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Factory to use when |
| 73 |
* creating XMLHttpRequest objects. |
| 74 |
* @constructor |
| 75 |
* @extends {goog.events.EventTarget} |
| 76 |
*/ |
| 77 |
goog.net.XhrIo = function(opt_xmlHttpFactory) { |
| 78 |
goog.net.XhrIo.base(this, 'constructor'); |
| 79 |
|
| 80 |
/** |
| 81 |
* Map of default headers to add to every request, use: |
| 82 |
* XhrIo.headers.set(name, value) |
| 83 |
* @type {!goog.structs.Map} |
| 84 |
*/ |
| 85 |
this.headers = new goog.structs.Map(); |
| 86 |
|
| 87 |
/** |
| 88 |
* Optional XmlHttpFactory |
| 89 |
* @private {goog.net.XmlHttpFactory} |
| 90 |
*/ |
| 91 |
this.xmlHttpFactory_ = opt_xmlHttpFactory || null; |
| 92 |
|
| 93 |
/** |
| 94 |
* Whether XMLHttpRequest is active. A request is active from the time send() |
| 95 |
* is called until onReadyStateChange() is complete, or error() or abort() |
| 96 |
* is called. |
| 97 |
* @private {boolean} |
| 98 |
*/ |
| 99 |
this.active_ = false; |
| 100 |
|
| 101 |
/** |
| 102 |
* The XMLHttpRequest object that is being used for the transfer. |
| 103 |
* @private {?goog.net.XhrLike.OrNative} |
| 104 |
*/ |
| 105 |
this.xhr_ = null; |
| 106 |
|
| 107 |
/** |
| 108 |
* The options to use with the current XMLHttpRequest object. |
| 109 |
* @private {Object} |
| 110 |
*/ |
| 111 |
this.xhrOptions_ = null; |
| 112 |
|
| 113 |
/** |
| 114 |
* Last URL that was requested. |
| 115 |
* @private {string|goog.Uri} |
| 116 |
*/ |
| 117 |
this.lastUri_ = ''; |
| 118 |
|
| 119 |
/** |
| 120 |
* Method for the last request. |
| 121 |
* @private {string} |
| 122 |
*/ |
| 123 |
this.lastMethod_ = ''; |
| 124 |
|
| 125 |
/** |
| 126 |
* Last error code. |
| 127 |
* @private {!goog.net.ErrorCode} |
| 128 |
*/ |
| 129 |
this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR; |
| 130 |
|
| 131 |
/** |
| 132 |
* Last error message. |
| 133 |
* @private {Error|string} |
| 134 |
*/ |
| 135 |
this.lastError_ = ''; |
| 136 |
|
| 137 |
/** |
| 138 |
* Used to ensure that we don't dispatch an multiple ERROR events. This can |
| 139 |
* happen in IE when it does a synchronous load and one error is handled in |
| 140 |
* the ready statte change and one is handled due to send() throwing an |
| 141 |
* exception. |
| 142 |
* @private {boolean} |
| 143 |
*/ |
| 144 |
this.errorDispatched_ = false; |
| 145 |
|
| 146 |
/** |
| 147 |
* Used to make sure we don't fire the complete event from inside a send call. |
| 148 |
* @private {boolean} |
| 149 |
*/ |
| 150 |
this.inSend_ = false; |
| 151 |
|
| 152 |
/** |
| 153 |
* Used in determining if a call to {@link #onReadyStateChange_} is from |
| 154 |
* within a call to this.xhr_.open. |
| 155 |
* @private {boolean} |
| 156 |
*/ |
| 157 |
this.inOpen_ = false; |
| 158 |
|
| 159 |
/** |
| 160 |
* Used in determining if a call to {@link #onReadyStateChange_} is from |
| 161 |
* within a call to this.xhr_.abort. |
| 162 |
* @private {boolean} |
| 163 |
*/ |
| 164 |
this.inAbort_ = false; |
| 165 |
|
| 166 |
/** |
| 167 |
* Number of milliseconds after which an incomplete request will be aborted |
| 168 |
* and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout |
| 169 |
* is set. |
| 170 |
* @private {number} |
| 171 |
*/ |
| 172 |
this.timeoutInterval_ = 0; |
| 173 |
|
| 174 |
/** |
| 175 |
* Timer to track request timeout. |
| 176 |
* @private {?number} |
| 177 |
*/ |
| 178 |
this.timeoutId_ = null; |
| 179 |
|
| 180 |
/** |
| 181 |
* The requested type for the response. The empty string means use the default |
| 182 |
* XHR behavior. |
| 183 |
* @private {goog.net.XhrIo.ResponseType} |
| 184 |
*/ |
| 185 |
this.responseType_ = goog.net.XhrIo.ResponseType.DEFAULT; |
| 186 |
|
| 187 |
/** |
| 188 |
* Whether a "credentialed" request is to be sent (one that is aware of |
| 189 |
* cookies and authentication). This is applicable only for cross-domain |
| 190 |
* requests and more recent browsers that support this part of the HTTP Access |
| 191 |
* Control standard. |
| 192 |
* |
| 193 |
* @see http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute |
| 194 |
* |
| 195 |
* @private {boolean} |
| 196 |
*/ |
| 197 |
this.withCredentials_ = false; |
| 198 |
|
| 199 |
/** |
| 200 |
* Whether progress events are enabled for this request. This is |
| 201 |
* disabled by default because setting a progress event handler |
| 202 |
* causes pre-flight OPTIONS requests to be sent for CORS requests, |
| 203 |
* even in cases where a pre-flight request would not otherwise be |
| 204 |
* sent. |
| 205 |
* |
| 206 |
* @see http://xhr.spec.whatwg.org/#security-considerations |
| 207 |
* |
| 208 |
* Note that this can cause problems for Firefox 22 and below, as an |
| 209 |
* older "LSProgressEvent" will be dispatched by the browser. That |
| 210 |
* progress event is no longer supported, and can lead to failures, |
| 211 |
* including throwing exceptions. |
| 212 |
* |
| 213 |
* @see http://bugzilla.mozilla.org/show_bug.cgi?id=845631 |
| 214 |
* @see b/23469793 |
| 215 |
* |
| 216 |
* @private {boolean} |
| 217 |
*/ |
| 218 |
this.progressEventsEnabled_ = false; |
| 219 |
|
| 220 |
/** |
| 221 |
* True if we can use XMLHttpRequest's timeout directly. |
| 222 |
* @private {boolean} |
| 223 |
*/ |
| 224 |
this.useXhr2Timeout_ = false; |
| 225 |
}; |
| 226 |
goog.inherits(goog.net.XhrIo, goog.events.EventTarget); |
| 227 |
|
| 228 |
|
| 229 |
/** |
| 230 |
* Response types that may be requested for XMLHttpRequests. |
| 231 |
* @enum {string} |
| 232 |
* @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetype-attribute |
| 233 |
*/ |
| 234 |
goog.net.XhrIo.ResponseType = { |
| 235 |
DEFAULT: '', |
| 236 |
TEXT: 'text', |
| 237 |
DOCUMENT: 'document', |
| 238 |
// Not supported as of Chrome 10.0.612.1 dev |
| 239 |
BLOB: 'blob', |
| 240 |
ARRAY_BUFFER: 'arraybuffer' |
| 241 |
}; |
| 242 |
|
| 243 |
|
| 244 |
/** |
| 245 |
* A reference to the XhrIo logger |
| 246 |
* @private {?goog.log.Logger} |
| 247 |
* @const |
| 248 |
*/ |
| 249 |
goog.net.XhrIo.prototype.logger_ = goog.log.getLogger('goog.net.XhrIo'); |
| 250 |
|
| 251 |
|
| 252 |
/** |
| 253 |
* The Content-Type HTTP header name |
| 254 |
* @type {string} |
| 255 |
*/ |
| 256 |
goog.net.XhrIo.CONTENT_TYPE_HEADER = 'Content-Type'; |
| 257 |
|
| 258 |
|
| 259 |
/** |
| 260 |
* The Content-Transfer-Encoding HTTP header name |
| 261 |
* @type {string} |
| 262 |
*/ |
| 263 |
goog.net.XhrIo.CONTENT_TRANSFER_ENCODING = 'Content-Transfer-Encoding'; |
| 264 |
|
| 265 |
|
| 266 |
/** |
| 267 |
* The pattern matching the 'http' and 'https' URI schemes |
| 268 |
* @type {!RegExp} |
| 269 |
*/ |
| 270 |
goog.net.XhrIo.HTTP_SCHEME_PATTERN = /^https?$/i; |
| 271 |
|
| 272 |
|
| 273 |
/** |
| 274 |
* The methods that typically come along with form data. We set different |
| 275 |
* headers depending on whether the HTTP action is one of these. |
| 276 |
* @type {!Array<string>} |
| 277 |
*/ |
| 278 |
goog.net.XhrIo.METHODS_WITH_FORM_DATA = ['POST', 'PUT']; |
| 279 |
|
| 280 |
|
| 281 |
/** |
| 282 |
* The Content-Type HTTP header value for a url-encoded form |
| 283 |
* @type {string} |
| 284 |
*/ |
| 285 |
goog.net.XhrIo.FORM_CONTENT_TYPE = |
| 286 |
'application/x-www-form-urlencoded;charset=utf-8'; |
| 287 |
|
| 288 |
|
| 289 |
/** |
| 290 |
* The XMLHttpRequest Level two timeout delay ms property name. |
| 291 |
* |
| 292 |
* @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute |
| 293 |
* |
| 294 |
* @private {string} |
| 295 |
* @const |
| 296 |
*/ |
| 297 |
goog.net.XhrIo.XHR2_TIMEOUT_ = 'timeout'; |
| 298 |
|
| 299 |
|
| 300 |
/** |
| 301 |
* The XMLHttpRequest Level two ontimeout handler property name. |
| 302 |
* |
| 303 |
* @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute |
| 304 |
* |
| 305 |
* @private {string} |
| 306 |
* @const |
| 307 |
*/ |
| 308 |
goog.net.XhrIo.XHR2_ON_TIMEOUT_ = 'ontimeout'; |
| 309 |
|
| 310 |
|
| 311 |
/** |
| 312 |
* All non-disposed instances of goog.net.XhrIo created |
| 313 |
* by {@link goog.net.XhrIo.send} are in this Array. |
| 314 |
* @see goog.net.XhrIo.cleanup |
| 315 |
* @private {!Array<!goog.net.XhrIo>} |
| 316 |
*/ |
| 317 |
goog.net.XhrIo.sendInstances_ = []; |
| 318 |
|
| 319 |
|
| 320 |
/** |
| 321 |
* Static send that creates a short lived instance of XhrIo to send the |
| 322 |
* request. |
| 323 |
* @see goog.net.XhrIo.cleanup |
| 324 |
* @param {string|goog.Uri} url Uri to make request to. |
| 325 |
* @param {?function(this:goog.net.XhrIo, ?)=} opt_callback Callback function |
| 326 |
* for when request is complete. |
| 327 |
* @param {string=} opt_method Send method, default: GET. |
| 328 |
* @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=} |
| 329 |
* opt_content Body data. |
| 330 |
* @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the |
| 331 |
* request. |
| 332 |
* @param {number=} opt_timeoutInterval Number of milliseconds after which an |
| 333 |
* incomplete request will be aborted; 0 means no timeout is set. |
| 334 |
* @param {boolean=} opt_withCredentials Whether to send credentials with the |
| 335 |
* request. Default to false. See {@link goog.net.XhrIo#setWithCredentials}. |
| 336 |
* @return {!goog.net.XhrIo} The sent XhrIo. |
| 337 |
*/ |
| 338 |
goog.net.XhrIo.send = function( |
| 339 |
url, opt_callback, opt_method, opt_content, opt_headers, |
| 340 |
opt_timeoutInterval, opt_withCredentials) { |
| 341 |
var x = new goog.net.XhrIo(); |
| 342 |
goog.net.XhrIo.sendInstances_.push(x); |
| 343 |
if (opt_callback) { |
| 344 |
x.listen(goog.net.EventType.COMPLETE, opt_callback); |
| 345 |
} |
| 346 |
x.listenOnce(goog.net.EventType.READY, x.cleanupSend_); |
| 347 |
if (opt_timeoutInterval) { |
| 348 |
x.setTimeoutInterval(opt_timeoutInterval); |
| 349 |
} |
| 350 |
if (opt_withCredentials) { |
| 351 |
x.setWithCredentials(opt_withCredentials); |
| 352 |
} |
| 353 |
x.send(url, opt_method, opt_content, opt_headers); |
| 354 |
return x; |
| 355 |
}; |
| 356 |
|
| 357 |
|
| 358 |
/** |
| 359 |
* Disposes all non-disposed instances of goog.net.XhrIo created by |
| 360 |
* {@link goog.net.XhrIo.send}. |
| 361 |
* {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance |
| 362 |
* it creates when the request completes or fails. However, if |
| 363 |
* the request never completes, then the goog.net.XhrIo is not disposed. |
| 364 |
* This can occur if the window is unloaded before the request completes. |
| 365 |
* We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo |
| 366 |
* it creates and make the client of {@link goog.net.XhrIo.send} be |
| 367 |
* responsible for disposing it in this case. However, this makes things |
| 368 |
* significantly more complicated for the client, and the whole point |
| 369 |
* of {@link goog.net.XhrIo.send} is that it's simple and easy to use. |
| 370 |
* Clients of {@link goog.net.XhrIo.send} should call |
| 371 |
* {@link goog.net.XhrIo.cleanup} when doing final |
| 372 |
* cleanup on window unload. |
| 373 |
*/ |
| 374 |
goog.net.XhrIo.cleanup = function() { |
| 375 |
var instances = goog.net.XhrIo.sendInstances_; |
| 376 |
while (instances.length) { |
| 377 |
instances.pop().dispose(); |
| 378 |
} |
| 379 |
}; |
| 380 |
|
| 381 |
|
| 382 |
/** |
| 383 |
* Installs exception protection for all entry point introduced by |
| 384 |
* goog.net.XhrIo instances which are not protected by |
| 385 |
* {@link goog.debug.ErrorHandler#protectWindowSetTimeout}, |
| 386 |
* {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or |
| 387 |
* {@link goog.events.protectBrowserEventEntryPoint}. |
| 388 |
* |
| 389 |
* @param {goog.debug.ErrorHandler} errorHandler Error handler with which to |
| 390 |
* protect the entry point(s). |
| 391 |
*/ |
| 392 |
goog.net.XhrIo.protectEntryPoints = function(errorHandler) { |
| 393 |
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = |
| 394 |
errorHandler.protectEntryPoint( |
| 395 |
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_); |
| 396 |
}; |
| 397 |
|
| 398 |
|
| 399 |
/** |
| 400 |
* Disposes of the specified goog.net.XhrIo created by |
| 401 |
* {@link goog.net.XhrIo.send} and removes it from |
| 402 |
* {@link goog.net.XhrIo.pendingStaticSendInstances_}. |
| 403 |
* @private |
| 404 |
*/ |
| 405 |
goog.net.XhrIo.prototype.cleanupSend_ = function() { |
| 406 |
this.dispose(); |
| 407 |
goog.array.remove(goog.net.XhrIo.sendInstances_, this); |
| 408 |
}; |
| 409 |
|
| 410 |
|
| 411 |
/** |
| 412 |
* Returns the number of milliseconds after which an incomplete request will be |
| 413 |
* aborted, or 0 if no timeout is set. |
| 414 |
* @return {number} Timeout interval in milliseconds. |
| 415 |
*/ |
| 416 |
goog.net.XhrIo.prototype.getTimeoutInterval = function() { |
| 417 |
return this.timeoutInterval_; |
| 418 |
}; |
| 419 |
|
| 420 |
|
| 421 |
/** |
| 422 |
* Sets the number of milliseconds after which an incomplete request will be |
| 423 |
* aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no |
| 424 |
* timeout is set. |
| 425 |
* @param {number} ms Timeout interval in milliseconds; 0 means none. |
| 426 |
*/ |
| 427 |
goog.net.XhrIo.prototype.setTimeoutInterval = function(ms) { |
| 428 |
this.timeoutInterval_ = Math.max(0, ms); |
| 429 |
}; |
| 430 |
|
| 431 |
|
| 432 |
/** |
| 433 |
* Sets the desired type for the response. At time of writing, this is only |
| 434 |
* supported in very recent versions of WebKit (10.0.612.1 dev and later). |
| 435 |
* |
| 436 |
* If this is used, the response may only be accessed via {@link #getResponse}. |
| 437 |
* |
| 438 |
* @param {goog.net.XhrIo.ResponseType} type The desired type for the response. |
| 439 |
*/ |
| 440 |
goog.net.XhrIo.prototype.setResponseType = function(type) { |
| 441 |
this.responseType_ = type; |
| 442 |
}; |
| 443 |
|
| 444 |
|
| 445 |
/** |
| 446 |
* Gets the desired type for the response. |
| 447 |
* @return {goog.net.XhrIo.ResponseType} The desired type for the response. |
| 448 |
*/ |
| 449 |
goog.net.XhrIo.prototype.getResponseType = function() { |
| 450 |
return this.responseType_; |
| 451 |
}; |
| 452 |
|
| 453 |
|
| 454 |
/** |
| 455 |
* Sets whether a "credentialed" request that is aware of cookie and |
| 456 |
* authentication information should be made. This option is only supported by |
| 457 |
* browsers that support HTTP Access Control. As of this writing, this option |
| 458 |
* is not supported in IE. |
| 459 |
* |
| 460 |
* @param {boolean} withCredentials Whether this should be a "credentialed" |
| 461 |
* request. |
| 462 |
*/ |
| 463 |
goog.net.XhrIo.prototype.setWithCredentials = function(withCredentials) { |
| 464 |
this.withCredentials_ = withCredentials; |
| 465 |
}; |
| 466 |
|
| 467 |
|
| 468 |
/** |
| 469 |
* Gets whether a "credentialed" request is to be sent. |
| 470 |
* @return {boolean} The desired type for the response. |
| 471 |
*/ |
| 472 |
goog.net.XhrIo.prototype.getWithCredentials = function() { |
| 473 |
return this.withCredentials_; |
| 474 |
}; |
| 475 |
|
| 476 |
|
| 477 |
/** |
| 478 |
* Sets whether progress events are enabled for this request. Note |
| 479 |
* that progress events require pre-flight OPTIONS request handling |
| 480 |
* for CORS requests, and may cause trouble with older browsers. See |
| 481 |
* progressEventsEnabled_ for details. |
| 482 |
* @param {boolean} enabled Whether progress events should be enabled. |
| 483 |
*/ |
| 484 |
goog.net.XhrIo.prototype.setProgressEventsEnabled = function(enabled) { |
| 485 |
this.progressEventsEnabled_ = enabled; |
| 486 |
}; |
| 487 |
|
| 488 |
|
| 489 |
/** |
| 490 |
* Gets whether progress events are enabled. |
| 491 |
* @return {boolean} Whether progress events are enabled for this request. |
| 492 |
*/ |
| 493 |
goog.net.XhrIo.prototype.getProgressEventsEnabled = function() { |
| 494 |
return this.progressEventsEnabled_; |
| 495 |
}; |
| 496 |
|
| 497 |
|
| 498 |
/** |
| 499 |
* Instance send that actually uses XMLHttpRequest to make a server call. |
| 500 |
* @param {string|goog.Uri} url Uri to make request to. |
| 501 |
* @param {string=} opt_method Send method, default: GET. |
| 502 |
* @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=} |
| 503 |
* opt_content Body data. |
| 504 |
* @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the |
| 505 |
* request. |
| 506 |
* @suppress {deprecated} Use deprecated goog.structs.forEach to allow different |
| 507 |
* types of parameters for opt_headers. |
| 508 |
*/ |
| 509 |
goog.net.XhrIo.prototype.send = function( |
| 510 |
url, opt_method, opt_content, opt_headers) { |
| 511 |
if (this.xhr_) { |
| 512 |
throw new Error( |
| 513 |
'[goog.net.XhrIo] Object is active with another request=' + |
| 514 |
this.lastUri_ + '; newUri=' + url); |
| 515 |
} |
| 516 |
|
| 517 |
var method = opt_method ? opt_method.toUpperCase() : 'GET'; |
| 518 |
|
| 519 |
this.lastUri_ = url; |
| 520 |
this.lastError_ = ''; |
| 521 |
this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR; |
| 522 |
this.lastMethod_ = method; |
| 523 |
this.errorDispatched_ = false; |
| 524 |
this.active_ = true; |
| 525 |
|
| 526 |
// Use the factory to create the XHR object and options |
| 527 |
this.xhr_ = this.createXhr(); |
| 528 |
this.xhrOptions_ = this.xmlHttpFactory_ ? this.xmlHttpFactory_.getOptions() : |
| 529 |
goog.net.XmlHttp.getOptions(); |
| 530 |
|
| 531 |
// Set up the onreadystatechange callback |
| 532 |
this.xhr_.onreadystatechange = goog.bind(this.onReadyStateChange_, this); |
| 533 |
|
| 534 |
// Set up upload/download progress events, if progress events are supported. |
| 535 |
if (this.getProgressEventsEnabled() && 'onprogress' in this.xhr_) { |
| 536 |
this.xhr_.onprogress = |
| 537 |
goog.bind(function(e) { this.onProgressHandler_(e, true); }, this); |
| 538 |
if (this.xhr_.upload) { |
| 539 |
this.xhr_.upload.onprogress = goog.bind(this.onProgressHandler_, this); |
| 540 |
} |
| 541 |
} |
| 542 |
|
| 543 |
/** |
| 544 |
* Try to open the XMLHttpRequest (always async), if an error occurs here it |
| 545 |
* is generally permission denied |
| 546 |
*/ |
| 547 |
try { |
| 548 |
goog.log.fine(this.logger_, this.formatMsg_('Opening Xhr')); |
| 549 |
this.inOpen_ = true; |
| 550 |
this.xhr_.open(method, String(url), true); // Always async! |
| 551 |
this.inOpen_ = false; |
| 552 |
} catch (err) { |
| 553 |
goog.log.fine( |
| 554 |
this.logger_, this.formatMsg_('Error opening Xhr: ' + err.message)); |
| 555 |
this.error_(goog.net.ErrorCode.EXCEPTION, err); |
| 556 |
return; |
| 557 |
} |
| 558 |
|
| 559 |
// We can't use null since this won't allow requests with form data to have a |
| 560 |
// content length specified which will cause some proxies to return a 411 |
| 561 |
// error. |
| 562 |
var content = opt_content || ''; |
| 563 |
|
| 564 |
var headers = this.headers.clone(); |
| 565 |
|
| 566 |
// Add headers specific to this request |
| 567 |
if (opt_headers) { |
| 568 |
goog.structs.forEach( |
| 569 |
opt_headers, function(value, key) { headers.set(key, value); }); |
| 570 |
} |
| 571 |
|
| 572 |
// Find whether a content type header is set, ignoring case. |
| 573 |
// HTTP header names are case-insensitive. See: |
| 574 |
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 |
| 575 |
var contentTypeKey = |
| 576 |
goog.array.find(headers.getKeys(), goog.net.XhrIo.isContentTypeHeader_); |
| 577 |
|
| 578 |
var contentIsFormData = |
| 579 |
(goog.global['FormData'] && (content instanceof goog.global['FormData'])); |
| 580 |
if (goog.array.contains(goog.net.XhrIo.METHODS_WITH_FORM_DATA, method) && |
| 581 |
!contentTypeKey && !contentIsFormData) { |
| 582 |
// For requests typically with form data, default to the url-encoded form |
| 583 |
// content type unless this is a FormData request. For FormData, |
| 584 |
// the browser will automatically add a multipart/form-data content type |
| 585 |
// with an appropriate multipart boundary. |
| 586 |
headers.set( |
| 587 |
goog.net.XhrIo.CONTENT_TYPE_HEADER, goog.net.XhrIo.FORM_CONTENT_TYPE); |
| 588 |
} |
| 589 |
|
| 590 |
// Add the headers to the Xhr object |
| 591 |
headers.forEach(function(value, key) { |
| 592 |
this.xhr_.setRequestHeader(key, value); |
| 593 |
}, this); |
| 594 |
|
| 595 |
if (this.responseType_) { |
| 596 |
this.xhr_.responseType = this.responseType_; |
| 597 |
} |
| 598 |
// Set xhr_.withCredentials only when the value is different, or else in |
| 599 |
// synchronous XMLHtppRequest.open Firefox will throw an exception. |
| 600 |
// https://bugzilla.mozilla.org/show_bug.cgi?id=736340 |
| 601 |
if ('withCredentials' in this.xhr_ && |
| 602 |
this.xhr_.withCredentials !== this.withCredentials_) { |
| 603 |
this.xhr_.withCredentials = this.withCredentials_; |
| 604 |
} |
| 605 |
|
| 606 |
/** |
| 607 |
* Try to send the request, or other wise report an error (404 not found). |
| 608 |
*/ |
| 609 |
try { |
| 610 |
this.cleanUpTimeoutTimer_(); // Paranoid, should never be running. |
| 611 |
if (this.timeoutInterval_ > 0) { |
| 612 |
this.useXhr2Timeout_ = goog.net.XhrIo.shouldUseXhr2Timeout_(this.xhr_); |
| 613 |
goog.log.fine( |
| 614 |
this.logger_, this.formatMsg_( |
| 615 |
'Will abort after ' + this.timeoutInterval_ + |
| 616 |
'ms if incomplete, xhr2 ' + this.useXhr2Timeout_)); |
| 617 |
if (this.useXhr2Timeout_) { |
| 618 |
this.xhr_[goog.net.XhrIo.XHR2_TIMEOUT_] = this.timeoutInterval_; |
| 619 |
this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] = |
| 620 |
goog.bind(this.timeout_, this); |
| 621 |
} else { |
| 622 |
this.timeoutId_ = |
| 623 |
goog.Timer.callOnce(this.timeout_, this.timeoutInterval_, this); |
| 624 |
} |
| 625 |
} |
| 626 |
goog.log.fine(this.logger_, this.formatMsg_('Sending request')); |
| 627 |
this.inSend_ = true; |
| 628 |
this.xhr_.send(content); |
| 629 |
this.inSend_ = false; |
| 630 |
|
| 631 |
} catch (err) { |
| 632 |
goog.log.fine(this.logger_, this.formatMsg_('Send error: ' + err.message)); |
| 633 |
this.error_(goog.net.ErrorCode.EXCEPTION, err); |
| 634 |
} |
| 635 |
}; |
| 636 |
|
| 637 |
|
| 638 |
/** |
| 639 |
* Determines if the argument is an XMLHttpRequest that supports the level 2 |
| 640 |
* timeout value and event. |
| 641 |
* |
| 642 |
* Currently, FF 21.0 OS X has the fields but won't actually call the timeout |
| 643 |
* handler. Perhaps the confusion in the bug referenced below hasn't |
| 644 |
* entirely been resolved. |
| 645 |
* |
| 646 |
* @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute |
| 647 |
* @see https://bugzilla.mozilla.org/show_bug.cgi?id=525816 |
| 648 |
* |
| 649 |
* @param {!goog.net.XhrLike.OrNative} xhr The request. |
| 650 |
* @return {boolean} True if the request supports level 2 timeout. |
| 651 |
* @private |
| 652 |
*/ |
| 653 |
goog.net.XhrIo.shouldUseXhr2Timeout_ = function(xhr) { |
| 654 |
return goog.userAgent.IE && goog.userAgent.isVersionOrHigher(9) && |
| 655 |
goog.isNumber(xhr[goog.net.XhrIo.XHR2_TIMEOUT_]) && |
| 656 |
goog.isDef(xhr[goog.net.XhrIo.XHR2_ON_TIMEOUT_]); |
| 657 |
}; |
| 658 |
|
| 659 |
|
| 660 |
/** |
| 661 |
* @param {string} header An HTTP header key. |
| 662 |
* @return {boolean} Whether the key is a content type header (ignoring |
| 663 |
* case. |
| 664 |
* @private |
| 665 |
*/ |
| 666 |
goog.net.XhrIo.isContentTypeHeader_ = function(header) { |
| 667 |
return goog.string.caseInsensitiveEquals( |
| 668 |
goog.net.XhrIo.CONTENT_TYPE_HEADER, header); |
| 669 |
}; |
| 670 |
|
| 671 |
|
| 672 |
/** |
| 673 |
* Creates a new XHR object. |
| 674 |
* @return {!goog.net.XhrLike.OrNative} The newly created XHR object. |
| 675 |
* @protected |
| 676 |
*/ |
| 677 |
goog.net.XhrIo.prototype.createXhr = function() { |
| 678 |
return this.xmlHttpFactory_ ? this.xmlHttpFactory_.createInstance() : |
| 679 |
goog.net.XmlHttp(); |
| 680 |
}; |
| 681 |
|
| 682 |
|
| 683 |
/** |
| 684 |
* The request didn't complete after {@link goog.net.XhrIo#timeoutInterval_} |
| 685 |
* milliseconds; raises a {@link goog.net.EventType.TIMEOUT} event and aborts |
| 686 |
* the request. |
| 687 |
* @private |
| 688 |
*/ |
| 689 |
goog.net.XhrIo.prototype.timeout_ = function() { |
| 690 |
if (typeof goog == 'undefined') { |
| 691 |
// If goog is undefined then the callback has occurred as the application |
| 692 |
// is unloading and will error. Thus we let it silently fail. |
| 693 |
} else if (this.xhr_) { |
| 694 |
this.lastError_ = |
| 695 |
'Timed out after ' + this.timeoutInterval_ + 'ms, aborting'; |
| 696 |
this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT; |
| 697 |
goog.log.fine(this.logger_, this.formatMsg_(this.lastError_)); |
| 698 |
this.dispatchEvent(goog.net.EventType.TIMEOUT); |
| 699 |
this.abort(goog.net.ErrorCode.TIMEOUT); |
| 700 |
} |
| 701 |
}; |
| 702 |
|
| 703 |
|
| 704 |
/** |
| 705 |
* Something errorred, so inactivate, fire error callback and clean up |
| 706 |
* @param {goog.net.ErrorCode} errorCode The error code. |
| 707 |
* @param {Error} err The error object. |
| 708 |
* @private |
| 709 |
*/ |
| 710 |
goog.net.XhrIo.prototype.error_ = function(errorCode, err) { |
| 711 |
this.active_ = false; |
| 712 |
if (this.xhr_) { |
| 713 |
this.inAbort_ = true; |
| 714 |
this.xhr_.abort(); // Ensures XHR isn't hung (FF) |
| 715 |
this.inAbort_ = false; |
| 716 |
} |
| 717 |
this.lastError_ = err; |
| 718 |
this.lastErrorCode_ = errorCode; |
| 719 |
this.dispatchErrors_(); |
| 720 |
this.cleanUpXhr_(); |
| 721 |
}; |
| 722 |
|
| 723 |
|
| 724 |
/** |
| 725 |
* Dispatches COMPLETE and ERROR in case of an error. This ensures that we do |
| 726 |
* not dispatch multiple error events. |
| 727 |
* @private |
| 728 |
*/ |
| 729 |
goog.net.XhrIo.prototype.dispatchErrors_ = function() { |
| 730 |
if (!this.errorDispatched_) { |
| 731 |
this.errorDispatched_ = true; |
| 732 |
this.dispatchEvent(goog.net.EventType.COMPLETE); |
| 733 |
this.dispatchEvent(goog.net.EventType.ERROR); |
| 734 |
} |
| 735 |
}; |
| 736 |
|
| 737 |
|
| 738 |
/** |
| 739 |
* Abort the current XMLHttpRequest |
| 740 |
* @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use - |
| 741 |
* defaults to ABORT. |
| 742 |
*/ |
| 743 |
goog.net.XhrIo.prototype.abort = function(opt_failureCode) { |
| 744 |
if (this.xhr_ && this.active_) { |
| 745 |
goog.log.fine(this.logger_, this.formatMsg_('Aborting')); |
| 746 |
this.active_ = false; |
| 747 |
this.inAbort_ = true; |
| 748 |
this.xhr_.abort(); |
| 749 |
this.inAbort_ = false; |
| 750 |
this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT; |
| 751 |
this.dispatchEvent(goog.net.EventType.COMPLETE); |
| 752 |
this.dispatchEvent(goog.net.EventType.ABORT); |
| 753 |
this.cleanUpXhr_(); |
| 754 |
} |
| 755 |
}; |
| 756 |
|
| 757 |
|
| 758 |
/** |
| 759 |
* Nullifies all callbacks to reduce risks of leaks. |
| 760 |
* @override |
| 761 |
* @protected |
| 762 |
*/ |
| 763 |
goog.net.XhrIo.prototype.disposeInternal = function() { |
| 764 |
if (this.xhr_) { |
| 765 |
// We explicitly do not call xhr_.abort() unless active_ is still true. |
| 766 |
// This is to avoid unnecessarily aborting a successful request when |
| 767 |
// dispose() is called in a callback triggered by a complete response, but |
| 768 |
// in which browser cleanup has not yet finished. |
| 769 |
// (See http://b/issue?id=1684217.) |
| 770 |
if (this.active_) { |
| 771 |
this.active_ = false; |
| 772 |
this.inAbort_ = true; |
| 773 |
this.xhr_.abort(); |
| 774 |
this.inAbort_ = false; |
| 775 |
} |
| 776 |
this.cleanUpXhr_(true); |
| 777 |
} |
| 778 |
|
| 779 |
goog.net.XhrIo.base(this, 'disposeInternal'); |
| 780 |
}; |
| 781 |
|
| 782 |
|
| 783 |
/** |
| 784 |
* Internal handler for the XHR object's readystatechange event. This method |
| 785 |
* checks the status and the readystate and fires the correct callbacks. |
| 786 |
* If the request has ended, the handlers are cleaned up and the XHR object is |
| 787 |
* nullified. |
| 788 |
* @private |
| 789 |
*/ |
| 790 |
goog.net.XhrIo.prototype.onReadyStateChange_ = function() { |
| 791 |
if (this.isDisposed()) { |
| 792 |
// This method is the target of an untracked goog.Timer.callOnce(). |
| 793 |
return; |
| 794 |
} |
| 795 |
if (!this.inOpen_ && !this.inSend_ && !this.inAbort_) { |
| 796 |
// Were not being called from within a call to this.xhr_.send |
| 797 |
// this.xhr_.abort, or this.xhr_.open, so this is an entry point |
| 798 |
this.onReadyStateChangeEntryPoint_(); |
| 799 |
} else { |
| 800 |
this.onReadyStateChangeHelper_(); |
| 801 |
} |
| 802 |
}; |
| 803 |
|
| 804 |
|
| 805 |
/** |
| 806 |
* Used to protect the onreadystatechange handler entry point. Necessary |
| 807 |
* as {#onReadyStateChange_} maybe called from within send or abort, this |
| 808 |
* method is only called when {#onReadyStateChange_} is called as an |
| 809 |
* entry point. |
| 810 |
* {@see #protectEntryPoints} |
| 811 |
* @private |
| 812 |
*/ |
| 813 |
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = function() { |
| 814 |
this.onReadyStateChangeHelper_(); |
| 815 |
}; |
| 816 |
|
| 817 |
|
| 818 |
/** |
| 819 |
* Helper for {@link #onReadyStateChange_}. This is used so that |
| 820 |
* entry point calls to {@link #onReadyStateChange_} can be routed through |
| 821 |
* {@link #onReadyStateChangeEntryPoint_}. |
| 822 |
* @private |
| 823 |
*/ |
| 824 |
goog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() { |
| 825 |
if (!this.active_) { |
| 826 |
// can get called inside abort call |
| 827 |
return; |
| 828 |
} |
| 829 |
|
| 830 |
if (typeof goog == 'undefined') { |
| 831 |
// NOTE(user): If goog is undefined then the callback has occurred as the |
| 832 |
// application is unloading and will error. Thus we let it silently fail. |
| 833 |
|
| 834 |
} else if ( |
| 835 |
this.xhrOptions_[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] && |
| 836 |
this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE && |
| 837 |
this.getStatus() == 2) { |
| 838 |
// NOTE(user): In IE if send() errors on a *local* request the readystate |
| 839 |
// is still changed to COMPLETE. We need to ignore it and allow the |
| 840 |
// try/catch around send() to pick up the error. |
| 841 |
goog.log.fine( |
| 842 |
this.logger_, |
| 843 |
this.formatMsg_('Local request error detected and ignored')); |
| 844 |
|
| 845 |
} else { |
| 846 |
// In IE when the response has been cached we sometimes get the callback |
| 847 |
// from inside the send call and this usually breaks code that assumes that |
| 848 |
// XhrIo is asynchronous. If that is the case we delay the callback |
| 849 |
// using a timer. |
| 850 |
if (this.inSend_ && |
| 851 |
this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE) { |
| 852 |
goog.Timer.callOnce(this.onReadyStateChange_, 0, this); |
| 853 |
return; |
| 854 |
} |
| 855 |
|
| 856 |
this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE); |
| 857 |
|
| 858 |
// readyState indicates the transfer has finished |
| 859 |
if (this.isComplete()) { |
| 860 |
goog.log.fine(this.logger_, this.formatMsg_('Request complete')); |
| 861 |
|
| 862 |
this.active_ = false; |
| 863 |
|
| 864 |
try { |
| 865 |
// Call the specific callbacks for success or failure. Only call the |
| 866 |
// success if the status is 200 (HTTP_OK) or 304 (HTTP_CACHED) |
| 867 |
if (this.isSuccess()) { |
| 868 |
this.dispatchEvent(goog.net.EventType.COMPLETE); |
| 869 |
this.dispatchEvent(goog.net.EventType.SUCCESS); |
| 870 |
} else { |
| 871 |
this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR; |
| 872 |
this.lastError_ = |
| 873 |
this.getStatusText() + ' [' + this.getStatus() + ']'; |
| 874 |
this.dispatchErrors_(); |
| 875 |
} |
| 876 |
} finally { |
| 877 |
this.cleanUpXhr_(); |
| 878 |
} |
| 879 |
} |
| 880 |
} |
| 881 |
}; |
| 882 |
|
| 883 |
|
| 884 |
/** |
| 885 |
* Internal handler for the XHR object's onprogress event. Fires both a generic |
| 886 |
* PROGRESS event and either a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event to |
| 887 |
* allow specific binding for each XHR progress event. |
| 888 |
* @param {!ProgressEvent} e XHR progress event. |
| 889 |
* @param {boolean=} opt_isDownload Whether the current progress event is from a |
| 890 |
* download. Used to determine whether DOWNLOAD_PROGRESS or UPLOAD_PROGRESS |
| 891 |
* event should be dispatched. |
| 892 |
* @private |
| 893 |
*/ |
| 894 |
goog.net.XhrIo.prototype.onProgressHandler_ = function(e, opt_isDownload) { |
| 895 |
goog.asserts.assert( |
| 896 |
e.type === goog.net.EventType.PROGRESS, |
| 897 |
'goog.net.EventType.PROGRESS is of the same type as raw XHR progress.'); |
| 898 |
this.dispatchEvent( |
| 899 |
goog.net.XhrIo.buildProgressEvent_(e, goog.net.EventType.PROGRESS)); |
| 900 |
this.dispatchEvent( |
| 901 |
goog.net.XhrIo.buildProgressEvent_( |
| 902 |
e, opt_isDownload ? goog.net.EventType.DOWNLOAD_PROGRESS : |
| 903 |
goog.net.EventType.UPLOAD_PROGRESS)); |
| 904 |
}; |
| 905 |
|
| 906 |
|
| 907 |
/** |
| 908 |
* Creates a representation of the native ProgressEvent. IE doesn't support |
| 909 |
* constructing ProgressEvent via "new", and the alternatives (e.g., |
| 910 |
* ProgressEvent.initProgressEvent) are non-standard or deprecated. |
| 911 |
* @param {!ProgressEvent} e XHR progress event. |
| 912 |
* @param {!goog.net.EventType} eventType The type of the event. |
| 913 |
* @return {!ProgressEvent} The progress event. |
| 914 |
* @private |
| 915 |
*/ |
| 916 |
goog.net.XhrIo.buildProgressEvent_ = function(e, eventType) { |
| 917 |
return /** @type {!ProgressEvent} */ ({ |
| 918 |
type: eventType, |
| 919 |
lengthComputable: e.lengthComputable, |
| 920 |
loaded: e.loaded, |
| 921 |
total: e.total |
| 922 |
}); |
| 923 |
}; |
| 924 |
|
| 925 |
|
| 926 |
/** |
| 927 |
* Remove the listener to protect against leaks, and nullify the XMLHttpRequest |
| 928 |
* object. |
| 929 |
* @param {boolean=} opt_fromDispose If this is from the dispose (don't want to |
| 930 |
* fire any events). |
| 931 |
* @private |
| 932 |
*/ |
| 933 |
goog.net.XhrIo.prototype.cleanUpXhr_ = function(opt_fromDispose) { |
| 934 |
if (this.xhr_) { |
| 935 |
// Cancel any pending timeout event handler. |
| 936 |
this.cleanUpTimeoutTimer_(); |
| 937 |
|
| 938 |
// Save reference so we can mark it as closed after the READY event. The |
| 939 |
// READY event may trigger another request, thus we must nullify this.xhr_ |
| 940 |
var xhr = this.xhr_; |
| 941 |
var clearedOnReadyStateChange = |
| 942 |
this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ? |
| 943 |
goog.nullFunction : |
| 944 |
null; |
| 945 |
this.xhr_ = null; |
| 946 |
this.xhrOptions_ = null; |
| 947 |
|
| 948 |
if (!opt_fromDispose) { |
| 949 |
this.dispatchEvent(goog.net.EventType.READY); |
| 950 |
} |
| 951 |
|
| 952 |
try { |
| 953 |
// NOTE(user): Not nullifying in FireFox can still leak if the callbacks |
| 954 |
// are defined in the same scope as the instance of XhrIo. But, IE doesn't |
| 955 |
// allow you to set the onreadystatechange to NULL so nullFunction is |
| 956 |
// used. |
| 957 |
xhr.onreadystatechange = clearedOnReadyStateChange; |
| 958 |
} catch (e) { |
| 959 |
// This seems to occur with a Gears HTTP request. Delayed the setting of |
| 960 |
// this onreadystatechange until after READY is sent out and catching the |
| 961 |
// error to see if we can track down the problem. |
| 962 |
goog.log.error( |
| 963 |
this.logger_, |
| 964 |
'Problem encountered resetting onreadystatechange: ' + e.message); |
| 965 |
} |
| 966 |
} |
| 967 |
}; |
| 968 |
|
| 969 |
|
| 970 |
/** |
| 971 |
* Make sure the timeout timer isn't running. |
| 972 |
* @private |
| 973 |
*/ |
| 974 |
goog.net.XhrIo.prototype.cleanUpTimeoutTimer_ = function() { |
| 975 |
if (this.xhr_ && this.useXhr2Timeout_) { |
| 976 |
this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] = null; |
| 977 |
} |
| 978 |
if (this.timeoutId_) { |
| 979 |
goog.Timer.clear(this.timeoutId_); |
| 980 |
this.timeoutId_ = null; |
| 981 |
} |
| 982 |
}; |
| 983 |
|
| 984 |
|
| 985 |
/** |
| 986 |
* @return {boolean} Whether there is an active request. |
| 987 |
*/ |
| 988 |
goog.net.XhrIo.prototype.isActive = function() { |
| 989 |
return !!this.xhr_; |
| 990 |
}; |
| 991 |
|
| 992 |
|
| 993 |
/** |
| 994 |
* @return {boolean} Whether the request has completed. |
| 995 |
*/ |
| 996 |
goog.net.XhrIo.prototype.isComplete = function() { |
| 997 |
return this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE; |
| 998 |
}; |
| 999 |
|
| 1000 |
|
| 1001 |
/** |
| 1002 |
* @return {boolean} Whether the request completed with a success. |
| 1003 |
*/ |
| 1004 |
goog.net.XhrIo.prototype.isSuccess = function() { |
| 1005 |
var status = this.getStatus(); |
| 1006 |
// A zero status code is considered successful for local files. |
| 1007 |
return goog.net.HttpStatus.isSuccess(status) || |
| 1008 |
status === 0 && !this.isLastUriEffectiveSchemeHttp_(); |
| 1009 |
}; |
| 1010 |
|
| 1011 |
|
| 1012 |
/** |
| 1013 |
* @return {boolean} whether the effective scheme of the last URI that was |
| 1014 |
* fetched was 'http' or 'https'. |
| 1015 |
* @private |
| 1016 |
*/ |
| 1017 |
goog.net.XhrIo.prototype.isLastUriEffectiveSchemeHttp_ = function() { |
| 1018 |
var scheme = goog.uri.utils.getEffectiveScheme(String(this.lastUri_)); |
| 1019 |
return goog.net.XhrIo.HTTP_SCHEME_PATTERN.test(scheme); |
| 1020 |
}; |
| 1021 |
|
| 1022 |
|
| 1023 |
/** |
| 1024 |
* Get the readystate from the Xhr object |
| 1025 |
* Will only return correct result when called from the context of a callback |
| 1026 |
* @return {goog.net.XmlHttp.ReadyState} goog.net.XmlHttp.ReadyState.*. |
| 1027 |
*/ |
| 1028 |
goog.net.XhrIo.prototype.getReadyState = function() { |
| 1029 |
return this.xhr_ ? |
| 1030 |
/** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) : |
| 1031 |
goog.net.XmlHttp.ReadyState |
| 1032 |
.UNINITIALIZED; |
| 1033 |
}; |
| 1034 |
|
| 1035 |
|
| 1036 |
/** |
| 1037 |
* Get the status from the Xhr object |
| 1038 |
* Will only return correct result when called from the context of a callback |
| 1039 |
* @return {number} Http status. |
| 1040 |
*/ |
| 1041 |
goog.net.XhrIo.prototype.getStatus = function() { |
| 1042 |
/** |
| 1043 |
* IE doesn't like you checking status until the readystate is greater than 2 |
| 1044 |
* (i.e. it is receiving or complete). The try/catch is used for when the |
| 1045 |
* page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_. |
| 1046 |
*/ |
| 1047 |
try { |
| 1048 |
return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ? |
| 1049 |
this.xhr_.status : |
| 1050 |
-1; |
| 1051 |
} catch (e) { |
| 1052 |
return -1; |
| 1053 |
} |
| 1054 |
}; |
| 1055 |
|
| 1056 |
|
| 1057 |
/** |
| 1058 |
* Get the status text from the Xhr object |
| 1059 |
* Will only return correct result when called from the context of a callback |
| 1060 |
* @return {string} Status text. |
| 1061 |
*/ |
| 1062 |
goog.net.XhrIo.prototype.getStatusText = function() { |
| 1063 |
/** |
| 1064 |
* IE doesn't like you checking status until the readystate is greater than 2 |
| 1065 |
* (i.e. it is receiving or complete). The try/catch is used for when the |
| 1066 |
* page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_. |
| 1067 |
*/ |
| 1068 |
try { |
| 1069 |
return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ? |
| 1070 |
this.xhr_.statusText : |
| 1071 |
''; |
| 1072 |
} catch (e) { |
| 1073 |
goog.log.fine(this.logger_, 'Can not get status: ' + e.message); |
| 1074 |
return ''; |
| 1075 |
} |
| 1076 |
}; |
| 1077 |
|
| 1078 |
|
| 1079 |
/** |
| 1080 |
* Get the last Uri that was requested |
| 1081 |
* @return {string} Last Uri. |
| 1082 |
*/ |
| 1083 |
goog.net.XhrIo.prototype.getLastUri = function() { |
| 1084 |
return String(this.lastUri_); |
| 1085 |
}; |
| 1086 |
|
| 1087 |
|
| 1088 |
/** |
| 1089 |
* Get the response text from the Xhr object |
| 1090 |
* Will only return correct result when called from the context of a callback. |
| 1091 |
* @return {string} Result from the server, or '' if no result available. |
| 1092 |
*/ |
| 1093 |
goog.net.XhrIo.prototype.getResponseText = function() { |
| 1094 |
try { |
| 1095 |
return this.xhr_ ? this.xhr_.responseText : ''; |
| 1096 |
} catch (e) { |
| 1097 |
// http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute |
| 1098 |
// states that responseText should return '' (and responseXML null) |
| 1099 |
// when the state is not LOADING or DONE. Instead, IE can |
| 1100 |
// throw unexpected exceptions, for example when a request is aborted |
| 1101 |
// or no data is available yet. |
| 1102 |
goog.log.fine(this.logger_, 'Can not get responseText: ' + e.message); |
| 1103 |
return ''; |
| 1104 |
} |
| 1105 |
}; |
| 1106 |
|
| 1107 |
|
| 1108 |
/** |
| 1109 |
* Get the response body from the Xhr object. This property is only available |
| 1110 |
* in IE since version 7 according to MSDN: |
| 1111 |
* http://msdn.microsoft.com/en-us/library/ie/ms534368(v=vs.85).aspx |
| 1112 |
* Will only return correct result when called from the context of a callback. |
| 1113 |
* |
| 1114 |
* One option is to construct a VBArray from the returned object and convert |
| 1115 |
* it to a JavaScript array using the toArray method: |
| 1116 |
* {@code (new window['VBArray'](xhrIo.getResponseBody())).toArray()} |
| 1117 |
* This will result in an array of numbers in the range of [0..255] |
| 1118 |
* |
| 1119 |
* Another option is to use the VBScript CStr method to convert it into a |
| 1120 |
* string as outlined in http://stackoverflow.com/questions/1919972 |
| 1121 |
* |
| 1122 |
* @return {Object} Binary result from the server or null if not available. |
| 1123 |
*/ |
| 1124 |
goog.net.XhrIo.prototype.getResponseBody = function() { |
| 1125 |
|
| 1126 |
try { |
| 1127 |
if (this.xhr_ && 'responseBody' in this.xhr_) { |
| 1128 |
return this.xhr_['responseBody']; |
| 1129 |
} |
| 1130 |
} catch (e) { |
| 1131 |
// IE can throw unexpected exceptions, for example when a request is aborted |
| 1132 |
// or no data is yet available. |
| 1133 |
goog.log.fine(this.logger_, 'Can not get responseBody: ' + e.message); |
| 1134 |
} |
| 1135 |
return null; |
| 1136 |
}; |
| 1137 |
|
| 1138 |
|
| 1139 |
/** |
| 1140 |
* Get the response XML from the Xhr object |
| 1141 |
* Will only return correct result when called from the context of a callback. |
| 1142 |
* @return {Document} The DOM Document representing the XML file, or null |
| 1143 |
* if no result available. |
| 1144 |
*/ |
| 1145 |
goog.net.XhrIo.prototype.getResponseXml = function() { |
| 1146 |
|
| 1147 |
try { |
| 1148 |
return this.xhr_ ? this.xhr_.responseXML : null; |
| 1149 |
} catch (e) { |
| 1150 |
goog.log.fine(this.logger_, 'Can not get responseXML: ' + e.message); |
| 1151 |
return null; |
| 1152 |
} |
| 1153 |
}; |
| 1154 |
|
| 1155 |
|
| 1156 |
/** |
| 1157 |
* Get the response and evaluates it as JSON from the Xhr object |
| 1158 |
* Will only return correct result when called from the context of a callback |
| 1159 |
* @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for |
| 1160 |
* stripping of the response before parsing. This needs to be set only if |
| 1161 |
* your backend server prepends the same prefix string to the JSON response. |
| 1162 |
* @throws Error if the response text is invalid JSON. |
| 1163 |
* @return {Object|undefined} JavaScript object. |
| 1164 |
*/ |
| 1165 |
goog.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) { |
| 1166 |
if (!this.xhr_) { |
| 1167 |
return undefined; |
| 1168 |
} |
| 1169 |
|
| 1170 |
var responseText = this.xhr_.responseText; |
| 1171 |
if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) { |
| 1172 |
responseText = responseText.substring(opt_xssiPrefix.length); |
| 1173 |
} |
| 1174 |
|
| 1175 |
return goog.json.hybrid.parse(responseText); |
| 1176 |
}; |
| 1177 |
|
| 1178 |
|
| 1179 |
/** |
| 1180 |
* Get the response as the type specificed by {@link #setResponseType}. At time |
| 1181 |
* of writing, this is only directly supported in very recent versions of WebKit |
| 1182 |
* (10.0.612.1 dev and later). If the field is not supported directly, we will |
| 1183 |
* try to emulate it. |
| 1184 |
* |
| 1185 |
* Emulating the response means following the rules laid out at |
| 1186 |
* http://www.w3.org/TR/XMLHttpRequest/#the-response-attribute |
| 1187 |
* |
| 1188 |
* On browsers with no support for this (Chrome < 10, Firefox < 4, etc), only |
| 1189 |
* response types of DEFAULT or TEXT may be used, and the response returned will |
| 1190 |
* be the text response. |
| 1191 |
* |
| 1192 |
* On browsers with Mozilla's draft support for array buffers (Firefox 4, 5), |
| 1193 |
* only response types of DEFAULT, TEXT, and ARRAY_BUFFER may be used, and the |
| 1194 |
* response returned will be either the text response or the Mozilla |
| 1195 |
* implementation of the array buffer response. |
| 1196 |
* |
| 1197 |
* On browsers will full support, any valid response type supported by the |
| 1198 |
* browser may be used, and the response provided by the browser will be |
| 1199 |
* returned. |
| 1200 |
* |
| 1201 |
* @return {*} The response. |
| 1202 |
*/ |
| 1203 |
goog.net.XhrIo.prototype.getResponse = function() { |
| 1204 |
|
| 1205 |
try { |
| 1206 |
if (!this.xhr_) { |
| 1207 |
return null; |
| 1208 |
} |
| 1209 |
if ('response' in this.xhr_) { |
| 1210 |
return this.xhr_.response; |
| 1211 |
} |
| 1212 |
switch (this.responseType_) { |
| 1213 |
case goog.net.XhrIo.ResponseType.DEFAULT: |
| 1214 |
case goog.net.XhrIo.ResponseType.TEXT: |
| 1215 |
return this.xhr_.responseText; |
| 1216 |
// DOCUMENT and BLOB don't need to be handled here because they are |
| 1217 |
// introduced in the same spec that adds the .response field, and would |
| 1218 |
// have been caught above. |
| 1219 |
// ARRAY_BUFFER needs an implementation for Firefox 4, where it was |
| 1220 |
// implemented using a draft spec rather than the final spec. |
| 1221 |
case goog.net.XhrIo.ResponseType.ARRAY_BUFFER: |
| 1222 |
if ('mozResponseArrayBuffer' in this.xhr_) { |
| 1223 |
return this.xhr_.mozResponseArrayBuffer; |
| 1224 |
} |
| 1225 |
} |
| 1226 |
// Fell through to a response type that is not supported on this browser. |
| 1227 |
goog.log.error( |
| 1228 |
this.logger_, 'Response type ' + this.responseType_ + ' is not ' + |
| 1229 |
'supported on this browser'); |
| 1230 |
return null; |
| 1231 |
} catch (e) { |
| 1232 |
goog.log.fine(this.logger_, 'Can not get response: ' + e.message); |
| 1233 |
return null; |
| 1234 |
} |
| 1235 |
}; |
| 1236 |
|
| 1237 |
|
| 1238 |
/** |
| 1239 |
* Get the value of the response-header with the given name from the Xhr object |
| 1240 |
* Will only return correct result when called from the context of a callback |
| 1241 |
* and the request has completed |
| 1242 |
* @param {string} key The name of the response-header to retrieve. |
| 1243 |
* @return {string|undefined} The value of the response-header named key. |
| 1244 |
*/ |
| 1245 |
goog.net.XhrIo.prototype.getResponseHeader = function(key) { |
| 1246 |
if (!this.xhr_ || !this.isComplete()) { |
| 1247 |
return undefined; |
| 1248 |
} |
| 1249 |
|
| 1250 |
var value = this.xhr_.getResponseHeader(key); |
| 1251 |
return goog.isNull(value) ? undefined : value; |
| 1252 |
}; |
| 1253 |
|
| 1254 |
|
| 1255 |
/** |
| 1256 |
* Gets the text of all the headers in the response. |
| 1257 |
* Will only return correct result when called from the context of a callback |
| 1258 |
* and the request has completed. |
| 1259 |
* @return {string} The value of the response headers or empty string. |
| 1260 |
*/ |
| 1261 |
goog.net.XhrIo.prototype.getAllResponseHeaders = function() { |
| 1262 |
return this.xhr_ && this.isComplete() ? this.xhr_.getAllResponseHeaders() : |
| 1263 |
''; |
| 1264 |
}; |
| 1265 |
|
| 1266 |
|
| 1267 |
/** |
| 1268 |
* Returns all response headers as a key-value map. |
| 1269 |
* Multiple values for the same header key can be combined into one, |
| 1270 |
* separated by a comma and a space. |
| 1271 |
* Note that the native getResponseHeader method for retrieving a single header |
| 1272 |
* does a case insensitive match on the header name. This method does not |
| 1273 |
* include any case normalization logic, it will just return a key-value |
| 1274 |
* representation of the headers. |
| 1275 |
* See: http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method |
| 1276 |
* @return {!Object<string, string>} An object with the header keys as keys |
| 1277 |
* and header values as values. |
| 1278 |
*/ |
| 1279 |
goog.net.XhrIo.prototype.getResponseHeaders = function() { |
| 1280 |
var headersObject = {}; |
| 1281 |
var headersArray = this.getAllResponseHeaders().split('\r\n'); |
| 1282 |
for (var i = 0; i < headersArray.length; i++) { |
| 1283 |
if (goog.string.isEmptyOrWhitespace(headersArray[i])) { |
| 1284 |
continue; |
| 1285 |
} |
| 1286 |
var keyValue = goog.string.splitLimit(headersArray[i], ': ', 2); |
| 1287 |
if (headersObject[keyValue[0]]) { |
| 1288 |
headersObject[keyValue[0]] += ', ' + keyValue[1]; |
| 1289 |
} else { |
| 1290 |
headersObject[keyValue[0]] = keyValue[1]; |
| 1291 |
} |
| 1292 |
} |
| 1293 |
return headersObject; |
| 1294 |
}; |
| 1295 |
|
| 1296 |
|
| 1297 |
/** |
| 1298 |
* Get the value of the response-header with the given name from the Xhr object. |
| 1299 |
* As opposed to {@link #getResponseHeader}, this method does not require that |
| 1300 |
* the request has completed. |
| 1301 |
* @param {string} key The name of the response-header to retrieve. |
| 1302 |
* @return {?string} The value of the response-header, or null if it is |
| 1303 |
* unavailable. |
| 1304 |
*/ |
| 1305 |
goog.net.XhrIo.prototype.getStreamingResponseHeader = function(key) { |
| 1306 |
return this.xhr_ ? this.xhr_.getResponseHeader(key) : null; |
| 1307 |
}; |
| 1308 |
|
| 1309 |
|
| 1310 |
/** |
| 1311 |
* Gets the text of all the headers in the response. As opposed to |
| 1312 |
* {@link #getAllResponseHeaders}, this method does not require that the request |
| 1313 |
* has completed. |
| 1314 |
* @return {string} The value of the response headers or empty string. |
| 1315 |
*/ |
| 1316 |
goog.net.XhrIo.prototype.getAllStreamingResponseHeaders = function() { |
| 1317 |
return this.xhr_ ? this.xhr_.getAllResponseHeaders() : ''; |
| 1318 |
}; |
| 1319 |
|
| 1320 |
|
| 1321 |
/** |
| 1322 |
* Get the last error message |
| 1323 |
* @return {goog.net.ErrorCode} Last error code. |
| 1324 |
*/ |
| 1325 |
goog.net.XhrIo.prototype.getLastErrorCode = function() { |
| 1326 |
return this.lastErrorCode_; |
| 1327 |
}; |
| 1328 |
|
| 1329 |
|
| 1330 |
/** |
| 1331 |
* Get the last error message |
| 1332 |
* @return {string} Last error message. |
| 1333 |
*/ |
| 1334 |
goog.net.XhrIo.prototype.getLastError = function() { |
| 1335 |
return goog.isString(this.lastError_) ? this.lastError_ : |
| 1336 |
String(this.lastError_); |
| 1337 |
}; |
| 1338 |
|
| 1339 |
|
| 1340 |
/** |
| 1341 |
* Adds the last method, status and URI to the message. This is used to add |
| 1342 |
* this information to the logging calls. |
| 1343 |
* @param {string} msg The message text that we want to add the extra text to. |
| 1344 |
* @return {string} The message with the extra text appended. |
| 1345 |
* @private |
| 1346 |
*/ |
| 1347 |
goog.net.XhrIo.prototype.formatMsg_ = function(msg) { |
| 1348 |
return msg + ' [' + this.lastMethod_ + ' ' + this.lastUri_ + ' ' + |
| 1349 |
this.getStatus() + ']'; |
| 1350 |
}; |
| 1351 |
|
| 1352 |
|
| 1353 |
// Register the xhr handler as an entry point, so that |
| 1354 |
// it can be monitored for exception handling, etc. |
| 1355 |
goog.debug.entryPointRegistry.register( |
| 1356 |
/** |
| 1357 |
* @param {function(!Function): !Function} transformer The transforming |
| 1358 |
* function. |
| 1359 |
*/ |
| 1360 |
function(transformer) { |
| 1361 |
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = |
| 1362 |
transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_); |
| 1363 |
}); |