Debian Codegraph @

closure-library/closure/goog/net/corsxmlhttpfactory.js

raw
1 // Copyright 2013 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 This file contain classes that add support for cross-domain XHR
17 * requests (see http://www.w3.org/TR/cors/). Most modern browsers are able to
18 * use a regular XMLHttpRequest for that, but IE 8 use XDomainRequest object
19 * instead. This file provides an adapter from this object to a goog.net.XhrLike
20 * and a factory to allow using this with a goog.net.XhrIo instance.
21 *
22 * IE 7 and older versions are not supported (given that they do not support
23 * CORS requests).
24 */
25 goog.provide('goog.net.CorsXmlHttpFactory');
26 goog.provide('goog.net.IeCorsXhrAdapter');
27
28 goog.require('goog.net.HttpStatus');
29 goog.require('goog.net.XhrLike');
30 goog.require('goog.net.XmlHttp');
31 goog.require('goog.net.XmlHttpFactory');
32
33
34
35 /**
36 * A factory of XML http request objects that supports cross domain requests.
37 * This class should be instantiated and passed as the parameter of a
38 * goog.net.XhrIo constructor to allow cross-domain requests in every browser.
39 *
40 * @extends {goog.net.XmlHttpFactory}
41 * @constructor
42 * @final
43 */
44 goog.net.CorsXmlHttpFactory = function() {
45 goog.net.XmlHttpFactory.call(this);
46 };
47 goog.inherits(goog.net.CorsXmlHttpFactory, goog.net.XmlHttpFactory);
48
49
50 /** @override */
51 goog.net.CorsXmlHttpFactory.prototype.createInstance = function() {
52 var xhr = new XMLHttpRequest();
53 if (('withCredentials' in xhr)) {
54 return xhr;
55 } else if (typeof XDomainRequest != 'undefined') {
56 return new goog.net.IeCorsXhrAdapter();
57 } else {
58 throw new Error('Unsupported browser');
59 }
60 };
61
62
63 /** @override */
64 goog.net.CorsXmlHttpFactory.prototype.internalGetOptions = function() {
65 return {};
66 };
67
68
69
70 /**
71 * An adapter around Internet Explorer's XDomainRequest object that makes it
72 * look like a standard XMLHttpRequest. This can be used instead of
73 * XMLHttpRequest to support CORS.
74 *
75 * @implements {goog.net.XhrLike}
76 * @constructor
77 * @struct
78 * @final
79 */
80 goog.net.IeCorsXhrAdapter = function() {
81 /**
82 * The underlying XDomainRequest used to make the HTTP request.
83 * @type {!XDomainRequest}
84 * @private
85 */
86 this.xdr_ = new XDomainRequest();
87
88 /**
89 * The simulated ready state.
90 * @type {number}
91 */
92 this.readyState = goog.net.XmlHttp.ReadyState.UNINITIALIZED;
93
94 /**
95 * The simulated ready state change callback function.
96 * @type {Function}
97 */
98 this.onreadystatechange = null;
99
100 /**
101 * The simulated response text parameter.
102 * @type {string}
103 */
104 this.responseText = '';
105
106 /**
107 * The simulated status code
108 * @type {number}
109 */
110 this.status = -1;
111
112 /** @override */
113 this.responseXML = null;
114
115 /** @override */
116 this.statusText = null;
117
118 this.xdr_.onload = goog.bind(this.handleLoad_, this);
119 this.xdr_.onerror = goog.bind(this.handleError_, this);
120 this.xdr_.onprogress = goog.bind(this.handleProgress_, this);
121 this.xdr_.ontimeout = goog.bind(this.handleTimeout_, this);
122 };
123
124
125 /**
126 * Opens a connection to the provided URL.
127 * @param {string} method The HTTP method to use. Valid methods include GET and
128 * POST.
129 * @param {string} url The URL to contact. The authority of this URL must match
130 * the authority of the current page's URL (e.g. http or https).
131 * @param {?boolean=} opt_async Whether the request is asynchronous, defaulting
132 * to true. XDomainRequest does not support syncronous requests, so setting
133 * it to false will actually raise an exception.
134 * @override
135 */
136 goog.net.IeCorsXhrAdapter.prototype.open = function(method, url, opt_async) {
137 if (goog.isDefAndNotNull(opt_async) && (!opt_async)) {
138 throw new Error('Only async requests are supported.');
139 }
140 this.xdr_.open(method, url);
141 };
142
143
144 /**
145 * Sends the request to the remote server. Before calling this function, always
146 * call {@link open}.
147 * @param {(ArrayBuffer|ArrayBufferView|Blob|Document|FormData|null|string)=}
148 * opt_content The content to send as POSTDATA, if any. Only string data is
149 * supported by this implementation.
150 * @override
151 */
152 goog.net.IeCorsXhrAdapter.prototype.send = function(opt_content) {
153 if (opt_content) {
154 if (typeof opt_content == 'string') {
155 this.xdr_.send(opt_content);
156 } else {
157 throw new Error('Only string data is supported');
158 }
159 } else {
160 this.xdr_.send();
161 }
162 };
163
164
165 /**
166 * @override
167 */
168 goog.net.IeCorsXhrAdapter.prototype.abort = function() {
169 this.xdr_.abort();
170 };
171
172
173 /**
174 * Sets a request header to send to the remote server. Because this
175 * implementation does not support request headers, this function does nothing.
176 * @param {string} key The name of the HTTP header to set. Ignored.
177 * @param {string} value The value to set for the HTTP header. Ignored.
178 * @override
179 */
180 goog.net.IeCorsXhrAdapter.prototype.setRequestHeader = function(key, value) {
181 // Unsupported; ignore the header.
182 };
183
184
185 /**
186 * Returns the value of the response header identified by key. This
187 * implementation only supports the 'content-type' header.
188 * @param {string} key The request header to fetch. If this parameter is set to
189 * 'content-type' (case-insensitive), this function returns the value of
190 * the 'content-type' request header. If this parameter is set to any other
191 * value, this function always returns an empty string.
192 * @return {string} The value of the response header, or an empty string if key
193 * is not 'content-type' (case-insensitive).
194 * @override
195 */
196 goog.net.IeCorsXhrAdapter.prototype.getResponseHeader = function(key) {
197 if (key.toLowerCase() == 'content-type') {
198 return this.xdr_.contentType;
199 }
200 return '';
201 };
202
203
204 /**
205 * Handles a request that has fully loaded successfully.
206 * @private
207 */
208 goog.net.IeCorsXhrAdapter.prototype.handleLoad_ = function() {
209 // IE only calls onload if the status is 200, so the status code must be OK.
210 this.status = goog.net.HttpStatus.OK;
211 this.responseText = this.xdr_.responseText;
212 this.setReadyState_(goog.net.XmlHttp.ReadyState.COMPLETE);
213 };
214
215
216 /**
217 * Handles a request that has failed to load.
218 * @private
219 */
220 goog.net.IeCorsXhrAdapter.prototype.handleError_ = function() {
221 // IE doesn't tell us what the status code actually is (other than the fact
222 // that it is not 200), so simulate an INTERNAL_SERVER_ERROR.
223 this.status = goog.net.HttpStatus.INTERNAL_SERVER_ERROR;
224 this.responseText = '';
225 this.setReadyState_(goog.net.XmlHttp.ReadyState.COMPLETE);
226 };
227
228
229 /**
230 * Handles a request that timed out.
231 * @private
232 */
233 goog.net.IeCorsXhrAdapter.prototype.handleTimeout_ = function() {
234 this.handleError_();
235 };
236
237
238 /**
239 * Handles a request that is in the process of loading.
240 * @private
241 */
242 goog.net.IeCorsXhrAdapter.prototype.handleProgress_ = function() {
243 // IE only calls onprogress if the status is 200, so the status code must be
244 // OK.
245 this.status = goog.net.HttpStatus.OK;
246 this.setReadyState_(goog.net.XmlHttp.ReadyState.LOADING);
247 };
248
249
250 /**
251 * Sets this XHR's ready state and fires the onreadystatechange listener (if one
252 * is set).
253 * @param {number} readyState The new ready state.
254 * @private
255 */
256 goog.net.IeCorsXhrAdapter.prototype.setReadyState_ = function(readyState) {
257 this.readyState = readyState;
258 if (this.onreadystatechange) {
259 this.onreadystatechange();
260 }
261 };
262
263
264 /**
265 * Returns the response headers from the server. This implemntation only returns
266 * the 'content-type' header.
267 * @return {string} The headers returned from the server.
268 * @override
269 */
270 goog.net.IeCorsXhrAdapter.prototype.getAllResponseHeaders = function() {
271 return 'content-type: ' + this.xdr_.contentType;
272 };