-
Notifications
You must be signed in to change notification settings - Fork 1k
/
iframeio.js
1425 lines (1195 loc) · 42.1 KB
/
iframeio.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Class for managing requests via iFrames. Supports a number of
* methods of transfer.
*
* Gets and Posts can be performed and the resultant page read in as text,
* JSON, or from the HTML DOM.
*
* Using an iframe causes the throbber to spin, this is good for providing
* feedback to the user that an action has occurred.
*
* Requests do not affect the history stack, see goog.History if you require
* this behavior.
*
* The responseText and responseJson methods assume the response is plain,
* text. You can access the Iframe's DOM through responseXml if you need
* access to the raw HTML.
*
* Tested:
* + FF2.0 (Win Linux)
* + IE6, IE7
* + Opera 9.1,
* + Chrome
* - Opera 8.5 fails because of no textContent and buggy innerText support
*
* NOTE: Safari doesn't fire the onload handler when loading plain text files
*
* This has been tested with Drip in IE to ensure memory usage is as constant
* as possible. When making making thousands of requests, memory usage stays
* constant for a while but then starts increasing (<500k for 2000
* requests) -- this hasn't yet been tracked down yet, though it is cleared up
* after a refresh.
*
*
* BACKGROUND FILE UPLOAD:
* By posting an arbitrary form through an IframeIo object, it is possible to
* implement background file uploads. Here's how to do it:
*
* - Create a form:
* <pre>
* <form id="form" enctype="multipart/form-data" method="POST">
* <input name="userfile" type="file" />
* </form>
* </pre>
*
* - Have the user click the file input
* - Create an IframeIo instance
* <pre>
* var io = new goog.net.IframeIo;
* goog.events.listen(io, goog.net.EventType.COMPLETE,
* function() { alert('Sent'); });
* io.sendFromForm(document.getElementById('form'));
* </pre>
*
*
* INCREMENTAL LOADING:
* Gmail sends down multiple script blocks which get executed as they are
* received by the client. This allows incremental rendering of the thread
* list and conversations.
*
* This requires collaboration with the server that is sending the requested
* page back. To set incremental loading up, you should:
*
* A) In the application code there should be an externed reference to
* <code>handleIncrementalData()</code>. e.g.
* goog.exportSymbol('GG_iframeFn', goog.net.IframeIo.handleIncrementalData);
*
* B) The response page should them call this method directly, an example
* response would look something like this:
* <pre>
* <html>
* <head>
* <meta content="text/html;charset=UTF-8" http-equiv="content-type">
* </head>
* <body>
* <script>
* D = top.P ? function(d) { top.GG_iframeFn(window, d) } : function() {};
* </script>
*
* <script>D([1, 2, 3, 4, 5]);</script>
* <script>D([6, 7, 8, 9, 10]);</script>
* <script>D([11, 12, 13, 14, 15]);</script>
* </body>
* </html>
* </pre>
*
* Your application should then listen, on the IframeIo instance, to the event
* goog.net.EventType.INCREMENTAL_DATA. The event object contains a
* 'data' member which is the content from the D() calls above.
*
* NOTE: There can be problems if you save a reference to the data object in IE.
* If you save an array, and the iframe is dispose, then the array looses its
* prototype and thus array methods like .join(). You can get around this by
* creating arrays using the parent window's Array constructor, or you can
* clone the array.
*
*
* EVENT MODEL:
* The various send methods work asynchronously. You can be notified about
* the current status of the request (completed, success or error) by
* listening for events on the IframeIo object itself. The following events
* will be sent:
* - goog.net.EventType.COMPLETE: when the request is completed
* (either successfully or unsuccessfully). You can find out about the result
* using the isSuccess() and getLastError
* methods.
* - goog.net.EventType.SUCCESS</code>: when the request was completed
* successfully
* - goog.net.EventType.ERROR: when the request failed
* - goog.net.EventType.ABORT: when the request has been aborted
*
* Example:
* <pre>
* var io = new goog.net.IframeIo();
* goog.events.listen(io, goog.net.EventType.COMPLETE,
* function() { alert('request complete'); });
* io.sendFromForm(...);
* </pre>
*
*/
goog.provide('goog.net.IframeIo');
goog.provide('goog.net.IframeIo.IncrementalDataEvent');
goog.require('goog.Timer');
goog.require('goog.Uri');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.debug.HtmlFormatter');
goog.require('goog.dom');
goog.require('goog.dom.InputType');
goog.require('goog.dom.TagName');
goog.require('goog.dom.safe');
goog.require('goog.events');
goog.require('goog.events.Event');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
goog.require('goog.html.uncheckedconversions');
goog.require('goog.json');
goog.require('goog.log');
goog.require('goog.log.Level');
goog.require('goog.net.ErrorCode');
goog.require('goog.net.EventType');
goog.require('goog.reflect');
goog.require('goog.string');
goog.require('goog.string.Const');
goog.require('goog.structs');
goog.require('goog.userAgent');
/**
* Class for managing requests via iFrames.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.net.IframeIo = function() {
goog.net.IframeIo.base(this, 'constructor');
/**
* Name for this IframeIo and frame
* @type {string}
* @private
*/
this.name_ = goog.net.IframeIo.getNextName_();
/**
* An array of iframes that have been finished with. We need them to be
* disposed async, so we don't confuse the browser (see below).
* @type {Array<Element>}
* @private
*/
this.iframesForDisposal_ = [];
// Create a lookup from names to instances of IframeIo. This is a helper
// function to be used in conjunction with goog.net.IframeIo.getInstanceByName
// to find the IframeIo object associated with a particular iframe. Used in
// incremental scripts etc.
goog.net.IframeIo.instances_[this.name_] = this;
};
goog.inherits(goog.net.IframeIo, goog.events.EventTarget);
/**
* Object used as a map to lookup instances of IframeIo objects by name.
* @type {Object}
* @private
*/
goog.net.IframeIo.instances_ = {};
/**
* Prefix for frame names
* @type {string}
*/
goog.net.IframeIo.FRAME_NAME_PREFIX = 'closure_frame';
/**
* Suffix that is added to inner frames used for sending requests in non-IE
* browsers
* @type {string}
*/
goog.net.IframeIo.INNER_FRAME_SUFFIX = '_inner';
/**
* The number of milliseconds after a request is completed to dispose the
* iframes. This can be done lazily so we wait long enough for any processing
* that occurred as a result of the response to finish.
* @type {number}
*/
goog.net.IframeIo.IFRAME_DISPOSE_DELAY_MS = 2000;
/**
* Counter used when creating iframes
* @type {number}
* @private
*/
goog.net.IframeIo.counter_ = 0;
/**
* Form element to post to.
* @type {HTMLFormElement}
* @private
*/
goog.net.IframeIo.form_;
/**
* Static send that creates a short lived instance of IframeIo to send the
* request.
* @param {goog.Uri|string} uri Uri of the request, it is up the caller to
* manage query string params.
* @param {Function=} opt_callback Event handler for when request is completed.
* @param {string=} opt_method Default is GET, POST uses a form to submit the
* request.
* @param {boolean=} opt_noCache Append a timestamp to the request to avoid
* caching.
* @param {Object|goog.structs.Map=} opt_data Map of key-value pairs that
* will be posted to the server via the iframe's form.
*/
goog.net.IframeIo.send = function(
uri, opt_callback, opt_method, opt_noCache, opt_data) {
var io = new goog.net.IframeIo();
goog.events.listen(io, goog.net.EventType.READY, io.dispose, false, io);
if (opt_callback) {
goog.events.listen(io, goog.net.EventType.COMPLETE, opt_callback);
}
io.send(uri, opt_method, opt_noCache, opt_data);
};
/**
* Find an iframe by name (assumes the context is goog.global since that is
* where IframeIo's iframes are kept).
* @param {string} fname The name to find.
* @return {HTMLIFrameElement} The iframe element with that name.
*/
goog.net.IframeIo.getIframeByName = function(fname) {
return window.frames[fname];
};
/**
* Find an instance of the IframeIo object by name.
* @param {string} fname The name to find.
* @return {goog.net.IframeIo} The instance of IframeIo.
*/
goog.net.IframeIo.getInstanceByName = function(fname) {
return goog.net.IframeIo.instances_[fname];
};
/**
* Handles incremental data and routes it to the correct iframeIo instance.
* The HTML page requested by the IframeIo instance should contain script blocks
* that call an externed reference to this method.
* @param {Window} win The window object.
* @param {Object} data The data object.
*/
goog.net.IframeIo.handleIncrementalData = function(win, data) {
// If this is the inner-frame, then we need to use the parent instead.
var iframeName =
goog.string.endsWith(win.name, goog.net.IframeIo.INNER_FRAME_SUFFIX) ?
win.parent.name :
win.name;
var iframeIoName = iframeName.substring(0, iframeName.lastIndexOf('_'));
var iframeIo = goog.net.IframeIo.getInstanceByName(iframeIoName);
if (iframeIo && iframeName == iframeIo.iframeName_) {
iframeIo.handleIncrementalData_(data);
} else {
var logger = goog.log.getLogger('goog.net.IframeIo');
goog.log.info(logger, 'Incremental iframe data routed for unknown iframe');
}
};
/**
* @return {string} The next iframe name.
* @private
*/
goog.net.IframeIo.getNextName_ = function() {
return goog.net.IframeIo.FRAME_NAME_PREFIX + goog.net.IframeIo.counter_++;
};
/**
* Gets a static form, one for all instances of IframeIo since IE6 leaks form
* nodes that are created/removed from the document.
* @return {!HTMLFormElement} The static form.
* @private
*/
goog.net.IframeIo.getForm_ = function() {
if (!goog.net.IframeIo.form_) {
goog.net.IframeIo.form_ = goog.dom.createDom(goog.dom.TagName.FORM);
goog.net.IframeIo.form_.acceptCharset = 'utf-8';
// Hide the form and move it off screen
var s = goog.net.IframeIo.form_.style;
s.position = 'absolute';
s.visibility = 'hidden';
s.top = s.left = '-10px';
s.width = s.height = '10px';
s.overflow = 'hidden';
goog.dom.getDocument().body.appendChild(goog.net.IframeIo.form_);
}
return goog.net.IframeIo.form_;
};
/**
* Adds the key value pairs from a map like data structure to a form
* @param {HTMLFormElement} form The form to add to.
* @param {Object|goog.structs.Map|goog.Uri.QueryData} data The data to add.
* @private
*/
goog.net.IframeIo.addFormInputs_ = function(form, data) {
var helper = goog.dom.getDomHelper(form);
goog.structs.forEach(data, function(value, key) {
if (!goog.isArray(value)) {
value = [value];
}
goog.array.forEach(value, function(value) {
var inp = helper.createDom(
goog.dom.TagName.INPUT,
{'type': goog.dom.InputType.HIDDEN, 'name': key, 'value': value});
form.appendChild(inp);
});
});
};
/**
* @return {boolean} Whether we can use readyState to monitor iframe loading.
* @private
*/
goog.net.IframeIo.useIeReadyStateCodePath_ = function() {
// ReadyState is only available on iframes up to IE10.
return goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('11');
};
/**
* Reference to a logger for the IframeIo objects
* @type {goog.log.Logger}
* @private
*/
goog.net.IframeIo.prototype.logger_ = goog.log.getLogger('goog.net.IframeIo');
/**
* Reference to form element that gets reused for requests to the iframe.
* @type {HTMLFormElement}
* @private
*/
goog.net.IframeIo.prototype.form_ = null;
/**
* Reference to the iframe being used for the current request, or null if no
* request is currently active.
* @type {HTMLIFrameElement}
* @private
*/
goog.net.IframeIo.prototype.iframe_ = null;
/**
* Name of the iframe being used for the current request, or null if no
* request is currently active.
* @type {?string}
* @private
*/
goog.net.IframeIo.prototype.iframeName_ = null;
/**
* Next id so that iframe names are unique.
* @type {number}
* @private
*/
goog.net.IframeIo.prototype.nextIframeId_ = 0;
/**
* Whether the object is currently active with a request.
* @type {boolean}
* @private
*/
goog.net.IframeIo.prototype.active_ = false;
/**
* Whether the last request is complete.
* @type {boolean}
* @private
*/
goog.net.IframeIo.prototype.complete_ = false;
/**
* Whether the last request was a success.
* @type {boolean}
* @private
*/
goog.net.IframeIo.prototype.success_ = false;
/**
* The URI for the last request.
* @type {goog.Uri}
* @private
*/
goog.net.IframeIo.prototype.lastUri_ = null;
/**
* The text content of the last request.
* @type {?string}
* @private
*/
goog.net.IframeIo.prototype.lastContent_ = null;
/**
* Last error code
* @type {goog.net.ErrorCode}
* @private
*/
goog.net.IframeIo.prototype.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;
/**
* Window timeout ID used to detect when firefox silently fails.
* @type {?number}
* @private
*/
goog.net.IframeIo.prototype.firefoxSilentErrorTimeout_ = null;
/**
* Window timeout ID used by the timer that disposes the iframes.
* @type {?number}
* @private
*/
goog.net.IframeIo.prototype.iframeDisposalTimer_ = null;
/**
* This is used to ensure that we don't handle errors twice for the same error.
* We can reach the {@link #handleError_} method twice in IE if the form is
* submitted while IE is offline and the URL is not available.
* @type {boolean}
* @private
*/
goog.net.IframeIo.prototype.errorHandled_;
/**
* Whether to suppress the listeners that determine when the iframe loads.
* @type {boolean}
* @private
*/
goog.net.IframeIo.prototype.ignoreResponse_ = false;
/** @private {Function} */
goog.net.IframeIo.prototype.errorChecker_;
/** @private {Object} */
goog.net.IframeIo.prototype.lastCustomError_;
/** @private {?string} */
goog.net.IframeIo.prototype.lastContentHtml_;
/**
* Sends a request via an iframe.
*
* A HTML form is used and submitted to the iframe, this simplifies the
* difference between GET and POST requests. The iframe needs to be created and
* destroyed for each request otherwise the request will contribute to the
* history stack.
*
* sendFromForm does some clever trickery (thanks jlim) in non-IE browsers to
* stop a history entry being added for POST requests.
*
* @param {goog.Uri|string} uri Uri of the request.
* @param {string=} opt_method Default is GET, POST uses a form to submit the
* request.
* @param {boolean=} opt_noCache Append a timestamp to the request to avoid
* caching.
* @param {Object|goog.structs.Map=} opt_data Map of key-value pairs.
*/
goog.net.IframeIo.prototype.send = function(
uri, opt_method, opt_noCache, opt_data) {
if (this.active_) {
throw new Error('[goog.net.IframeIo] Unable to send, already active.');
}
var uriObj = new goog.Uri(uri);
this.lastUri_ = uriObj;
var method = opt_method ? opt_method.toUpperCase() : 'GET';
if (opt_noCache) {
uriObj.makeUnique();
}
goog.log.info(
this.logger_, 'Sending iframe request: ' + uriObj + ' [' + method + ']');
// Build a form for this request
this.form_ = goog.net.IframeIo.getForm_();
if (method == 'GET') {
// For GET requests, we assume that the caller didn't want the queryparams
// already specified in the URI to be clobbered by the form, so we add the
// params here.
goog.net.IframeIo.addFormInputs_(this.form_, uriObj.getQueryData());
}
if (opt_data) {
// Create form fields for each of the data values
goog.net.IframeIo.addFormInputs_(this.form_, opt_data);
}
// Set the URI that the form will be posted
this.form_.action = uriObj.toString();
this.form_.method = method;
this.sendFormInternal_();
this.clearForm_();
};
/**
* Sends the data stored in an existing form to the server. The HTTP method
* should be specified on the form, the action can also be specified but can
* be overridden by the optional URI param.
*
* This can be used in conjunction will a file-upload input to upload a file in
* the background without affecting history.
*
* Example form:
* <pre>
* <form action="/server/" enctype="multipart/form-data" method="POST">
* <input name="userfile" type="file">
* </form>
* </pre>
*
* @param {HTMLFormElement} form Form element used to send the request to the
* server.
* @param {string=} opt_uri Uri to set for the destination of the request, by
* default the uri will come from the form.
* @param {boolean=} opt_noCache Append a timestamp to the request to avoid
* caching.
*/
goog.net.IframeIo.prototype.sendFromForm = function(
form, opt_uri, opt_noCache) {
if (this.active_) {
throw new Error('[goog.net.IframeIo] Unable to send, already active.');
}
var uri = new goog.Uri(opt_uri || form.action);
if (opt_noCache) {
uri.makeUnique();
}
goog.log.info(this.logger_, 'Sending iframe request from form: ' + uri);
this.lastUri_ = uri;
this.form_ = form;
this.form_.action = uri.toString();
this.sendFormInternal_();
};
/**
* Abort the current Iframe request
* @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use -
* defaults to ABORT.
*/
goog.net.IframeIo.prototype.abort = function(opt_failureCode) {
if (this.active_) {
goog.log.info(this.logger_, 'Request aborted');
var requestIframe = this.getRequestIframe();
goog.asserts.assert(requestIframe);
goog.events.removeAll(requestIframe);
this.complete_ = false;
this.active_ = false;
this.success_ = false;
this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT;
this.dispatchEvent(goog.net.EventType.ABORT);
this.makeReady_();
}
};
/** @override */
goog.net.IframeIo.prototype.disposeInternal = function() {
goog.log.fine(this.logger_, 'Disposing iframeIo instance');
// If there is an active request, abort it
if (this.active_) {
goog.log.fine(this.logger_, 'Aborting active request');
this.abort();
}
// Call super-classes implementation (remove listeners)
goog.net.IframeIo.superClass_.disposeInternal.call(this);
// Add the current iframe to the list of iframes for disposal.
if (this.iframe_) {
this.scheduleIframeDisposal_();
}
// Disposes of the form
this.disposeForm_();
// Nullify anything that might cause problems and clear state
delete this.errorChecker_;
this.form_ = null;
this.lastCustomError_ = this.lastContent_ = this.lastContentHtml_ = null;
this.lastUri_ = null;
this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;
delete goog.net.IframeIo.instances_[this.name_];
};
/**
* @return {boolean} True if transfer is complete.
*/
goog.net.IframeIo.prototype.isComplete = function() {
return this.complete_;
};
/**
* @return {boolean} True if transfer was successful.
*/
goog.net.IframeIo.prototype.isSuccess = function() {
return this.success_;
};
/**
* @return {boolean} True if a transfer is in progress.
*/
goog.net.IframeIo.prototype.isActive = function() {
return this.active_;
};
/**
* Returns the last response text (i.e. the text content of the iframe).
* Assumes plain text!
* @return {?string} Result from the server.
*/
goog.net.IframeIo.prototype.getResponseText = function() {
return this.lastContent_;
};
/**
* Returns the last response html (i.e. the innerHtml of the iframe).
* @return {?string} Result from the server.
*/
goog.net.IframeIo.prototype.getResponseHtml = function() {
return this.lastContentHtml_;
};
/**
* Parses the content as JSON. This is a legacy method for browsers without
* JSON.parse or for responses that are not valid JSON (e.g. containing NaN).
* Use JSON.parse(this.getResponseText()) in the other cases.
* @return {Object} The parsed content.
*/
goog.net.IframeIo.prototype.getResponseJson = function() {
return goog.json.parse(this.lastContent_);
};
/**
* Returns the document object from the last request. Not truly XML, but
* used to mirror the XhrIo interface.
* @return {HTMLDocument} The document object from the last request.
*/
goog.net.IframeIo.prototype.getResponseXml = function() {
if (!this.iframe_) return null;
return this.getContentDocument_();
};
/**
* Get the uri of the last request.
* @return {goog.Uri} Uri of last request.
*/
goog.net.IframeIo.prototype.getLastUri = function() {
return this.lastUri_;
};
/**
* Gets the last error code.
* @return {goog.net.ErrorCode} Last error code.
*/
goog.net.IframeIo.prototype.getLastErrorCode = function() {
return this.lastErrorCode_;
};
/**
* Gets the last error message.
* @return {string} Last error message.
*/
goog.net.IframeIo.prototype.getLastError = function() {
return goog.net.ErrorCode.getDebugMessage(this.lastErrorCode_);
};
/**
* Gets the last custom error.
* @return {Object} Last custom error.
*/
goog.net.IframeIo.prototype.getLastCustomError = function() {
return this.lastCustomError_;
};
/**
* Sets the callback function used to check if a loaded IFrame is in an error
* state.
* @param {Function} fn Callback that expects a document object as it's single
* argument.
*/
goog.net.IframeIo.prototype.setErrorChecker = function(fn) {
this.errorChecker_ = fn;
};
/**
* Gets the callback function used to check if a loaded IFrame is in an error
* state.
* @return {Function} A callback that expects a document object as it's single
* argument.
*/
goog.net.IframeIo.prototype.getErrorChecker = function() {
return this.errorChecker_;
};
/**
* @return {boolean} Whether the server response is being ignored.
*/
goog.net.IframeIo.prototype.isIgnoringResponse = function() {
return this.ignoreResponse_;
};
/**
* Sets whether to ignore the response from the server by not adding any event
* handlers to fire when the iframe loads. This is necessary when using IframeIo
* to submit to a server on another domain, to avoid same-origin violations when
* trying to access the response. If this is set to true, the IframeIo instance
* will be a single-use instance that is only usable for one request. It will
* only clean up its resources (iframes and forms) when it is disposed.
* @param {boolean} ignore Whether to ignore the server response.
*/
goog.net.IframeIo.prototype.setIgnoreResponse = function(ignore) {
this.ignoreResponse_ = ignore;
};
/**
* Submits the internal form to the iframe.
* @private
* @suppress {strictMissingProperties} Part of the go/strict_warnings_migration
*/
goog.net.IframeIo.prototype.sendFormInternal_ = function() {
this.active_ = true;
this.complete_ = false;
this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;
// Make Iframe
this.createIframe_();
if (goog.net.IframeIo.useIeReadyStateCodePath_()) {
// In IE<11 we simply create the frame, wait until it is ready, then post
// the form to the iframe and wait for the readystate to change to
// 'complete'
// Set the target to the iframe's name
this.form_.target = this.iframeName_ || '';
this.appendIframe_();
if (!this.ignoreResponse_) {
goog.events.listen(
this.iframe_, goog.events.EventType.READYSTATECHANGE,
this.onIeReadyStateChange_, false, this);
}
try {
this.errorHandled_ = false;
this.form_.submit();
} catch (e) {
// If submit threw an exception then it probably means the page that the
// code is running on the local file system and the form's action was
// pointing to a file that doesn't exist, causing the browser to fire an
// exception. IE also throws an exception when it is working offline and
// the URL is not available.
if (!this.ignoreResponse_) {
goog.events.unlisten(
this.iframe_, goog.events.EventType.READYSTATECHANGE,
this.onIeReadyStateChange_, false, this);
}
this.handleError_(goog.net.ErrorCode.ACCESS_DENIED);
}
} else {
// For all other browsers we do some trickery to ensure that there is no
// entry on the history stack. Thanks go to jlim for the prototype for this
goog.log.fine(this.logger_, 'Setting up iframes and cloning form');
this.appendIframe_();
var innerFrameName =
this.iframeName_ + goog.net.IframeIo.INNER_FRAME_SUFFIX;
// Open and document.write another iframe into the iframe
var doc = goog.dom.getFrameContentDocument(this.iframe_);
var html;
if (document.baseURI) {
// On Safari 4 and 5 the new iframe doesn't inherit the current baseURI.
html = goog.net.IframeIo.createIframeHtmlWithBaseUri_(innerFrameName);
} else {
html = goog.net.IframeIo.createIframeHtml_(innerFrameName);
}
if (goog.userAgent.OPERA && !goog.userAgent.WEBKIT) {
// Presto based Opera adds a history entry when document.write is used.
// Change the innerHTML of the page instead.
goog.dom.safe.setInnerHtml(doc.documentElement, html);
} else {
goog.dom.safe.documentWrite(doc, html);
}
// Listen for the iframe's load
if (!this.ignoreResponse_) {
goog.events.listen(
doc.getElementById(innerFrameName), goog.events.EventType.LOAD,
this.onIframeLoaded_, false, this);
}
// Fix text areas, since importNode won't clone changes to the value
var textareas = goog.dom.getElementsByTagName(
goog.dom.TagName.TEXTAREA, goog.asserts.assert(this.form_));
for (var i = 0, n = textareas.length; i < n; i++) {
// The childnodes represent the initial child nodes for the text area
// appending a text node essentially resets the initial value ready for
// it to be clones - while maintaining HTML escaping.
var value = textareas[i].value;
if (goog.dom.getRawTextContent(textareas[i]) != value) {
goog.dom.setTextContent(textareas[i], value);
textareas[i].value = value;
}
}
// Append a cloned form to the iframe
var clone = doc.importNode(goog.asserts.assert(this.form_), true);
clone.target = innerFrameName;
// Work around crbug.com/66987
clone.action = this.form_.action;
doc.body.appendChild(clone);
// Fix select boxes, importNode won't override the default value
var selects = goog.dom.getElementsByTagName(
goog.dom.TagName.SELECT, goog.asserts.assert(this.form_));
var clones = goog.dom.getElementsByTagName(
goog.dom.TagName.SELECT, /** @type {!Element} */ (clone));
for (var i = 0, n = selects.length; i < n; i++) {
var selectsOptions =
goog.dom.getElementsByTagName(goog.dom.TagName.OPTION, selects[i]);
var clonesOptions =
goog.dom.getElementsByTagName(goog.dom.TagName.OPTION, clones[i]);
for (var j = 0, m = selectsOptions.length; j < m; j++) {
clonesOptions[j].selected = selectsOptions[j].selected;
}
}
// IE and some versions of Firefox (1.5 - 1.5.07?) fail to clone the value
// attribute for <input type="file"> nodes, which results in an empty
// upload if the clone is submitted. Check, and if the clone failed, submit
// using the original form instead.
var inputs = goog.dom.getElementsByTagName(
goog.dom.TagName.INPUT, goog.asserts.assert(this.form_));
var inputClones = goog.dom.getElementsByTagName(
goog.dom.TagName.INPUT, /** @type {!Element} */ (clone));
for (var i = 0, n = inputs.length; i < n; i++) {
if (inputs[i].type == goog.dom.InputType.FILE) {
if (inputs[i].value != inputClones[i].value) {
goog.log.fine(
this.logger_, 'File input value not cloned properly. Will ' +
'submit using original form.');
this.form_.target = innerFrameName;
clone = this.form_;
break;
}
}
}
goog.log.fine(this.logger_, 'Submitting form');
try {
this.errorHandled_ = false;
clone.submit();
doc.close();
if (goog.userAgent.GECKO) {
// This tests if firefox silently fails, this can happen, for example,
// when the server resets the connection because of a large file upload
this.firefoxSilentErrorTimeout_ =
goog.Timer.callOnce(this.testForFirefoxSilentError_, 250, this);
}
} catch (e) {
// If submit threw an exception then it probably means the page that the
// code is running on the local file system and the form's action was
// pointing to a file that doesn't exist, causing the browser to fire an
// exception.
goog.log.error(
this.logger_,
'Error when submitting form: ' +
goog.debug.HtmlFormatter.exposeException(e));
if (!this.ignoreResponse_) {
goog.events.unlisten(
doc.getElementById(innerFrameName), goog.events.EventType.LOAD,
this.onIframeLoaded_, false, this);
}
doc.close();
this.handleError_(goog.net.ErrorCode.FILE_NOT_FOUND);
}
}
};