-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
jquery.signalR.js
1168 lines (975 loc) · 46 KB
/
jquery.signalR.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
/*!
* SignalR JavaScript Library v0.5.1
* http://signalr.net/
*
* Copyright David Fowler and Damian Edwards 2012
* Licensed under the MIT.
* https://github.com/SignalR/SignalR/blob/master/LICENSE.md
*/
/// <reference path="jquery-1.6.2.js" />
(function ($, window) {
/// <param name="$" type="jQuery" />
"use strict";
if (typeof ($) !== "function") {
// no jQuery!
throw "SignalR: jQuery not found. Please ensure jQuery is referenced before the SignalR.js file.";
}
if (!window.JSON) {
// no JSON!
throw "SignalR: No JSON parser found. Please ensure json2.js is referenced before the SignalR.js file if you need to support clients without native JSON parsing support, e.g. IE<8.";
}
var signalR,
_connection,
events = {
onStart: "onStart",
onStarting: "onStarting",
onSending: "onSending",
onReceived: "onReceived",
onError: "onError",
onReconnect: "onReconnect",
onStateChanged: "onStateChanged",
onDisconnect: "onDisconnect"
},
log = function (msg, logging) {
if (logging === false) {
return;
}
var m;
if (typeof (window.console) === "undefined") {
return;
}
m = "[" + new Date().toTimeString() + "] SignalR: " + msg;
if (window.console.debug) {
window.console.debug(m);
} else if (window.console.log) {
window.console.log(m);
}
},
isCrossDomain = function (url) {
var link;
url = $.trim(url);
if (url.indexOf("http") !== 0) {
return false;
}
// Create an anchor tag.
link = window.document.createElement("a");
link.href = url;
return link.protocol + link.host !== window.location.protocol + window.location.host;
},
changeState = function (connection, state) {
if (state !== connection.state) {
// REVIEW: Should event fire before or after the state change actually occurs?
$(connection).trigger(events.onStateChanged, [{ oldState: connection.state, newState: state}]);
connection.state = state;
}
},
isDisconnecting = function (connection) {
return connection.state === signalR.connectionState.disconnecting ||
connection.state === signalR.connectionState.disconnected;
};
signalR = function (url, qs, logging) {
/// <summary>Creates a new SignalR connection for the given url</summary>
/// <param name="url" type="String">The URL of the long polling endpoint</param>
/// <param name="qs" type="Object">
/// [Optional] Custom querystring parameters to add to the connection URL.
/// If an object, every non-function member will be added to the querystring.
/// If a string, it's added to the QS as specified.
/// </param>
/// <param name="logging" type="Boolean">
/// [Optional] A flag indicating whether connection logging is enabled to the browser
/// console/log. Defaults to false.
/// </param>
/// <returns type="signalR" />
return new signalR.fn.init(url, qs, logging);
};
signalR.connectionState = {
connecting: 0,
connected: 1,
reconnecting: 2,
disconnecting: 3,
disconnected: 4
};
signalR.fn = signalR.prototype = {
init: function (url, qs, logging) {
this.url = url;
this.qs = qs;
if (typeof (logging) === "boolean") {
this.logging = logging;
}
},
ajaxDataType: "json",
logging: false,
state: signalR.connectionState.disconnected,
reconnectDelay: 2000,
start: function (options, callback) {
/// <summary>Starts the connection</summary>
/// <param name="options" type="Object">Options map</param>
/// <param name="callback" type="Function">A callback function to execute when the connection has started</param>
var connection = this,
config = {
transport: "auto",
jsonp: false
},
initialize,
deferred = $.Deferred(),
parser = window.document.createElement("a");
if (connection.state === signalR.connectionState.connecting ||
connection.state === signalR.connectionState.connected) {
// Already started, just return
deferred.resolve(connection);
return deferred.promise();
}
// Set the state to connecting
changeState(connection, signalR.connectionState.connecting);
if ($.type(options) === "function") {
// Support calling with single callback parameter
callback = options;
} else if ($.type(options) === "object") {
$.extend(config, options);
if ($.type(config.callback) === "function") {
callback = config.callback;
}
}
// Resolve the full url
parser.href = connection.url;
if (parser.protocol === ":") {
connection.baseUrl = window.document.location.protocol + "//" + window.document.location.host;
}
else {
connection.baseUrl = parser.protocol + "//" + parser.host;
}
if (isCrossDomain(connection.url)) {
connection.log("Auto detected cross domain url.");
if (config.transport === "auto") {
// If you didn't say you wanted to use jsonp, determine if it's your only choice
// i.e. if your browser doesn't supports CORS
if (!config.jsonp) {
config.jsonp = !$.support.cors;
if (config.jsonp) {
connection.log("Using jsonp because this browser doesn't support CORS");
}
}
// If we're using jsonp thn just change to longpolling
if (config.jsonp === true) {
config.transport = "longPolling";
}
else {
// Otherwise try webSockets and longPolling since SSE doesn't support CORS
// TODO: Support XDM with foreverFrame
config.transport = ["webSockets", "longPolling"];
}
}
}
connection.ajaxDataType = config.jsonp ? "jsonp" : "json";
$(connection).bind(events.onStart, function (e, data) {
if ($.type(callback) === "function") {
callback.call(connection);
}
deferred.resolve(connection);
});
initialize = function (transports, index) {
index = index || 0;
if (index >= transports.length) {
if (!connection.transport) {
// No transport initialized successfully
deferred.reject("SignalR: No transport could be initialized successfully. Try specifying a different transport or none at all for auto initialization.");
}
return;
}
var transportName = transports[index],
transport = $.type(transportName) === "object" ? transportName : signalR.transports[transportName];
transport.start(connection, function () { // success
connection.transport = transport;
changeState(connection, signalR.connectionState.connected);
$(connection).trigger(events.onStart);
$(window).unload(function () { // failure
connection.stop(false /* async */);
});
}, function () {
initialize(transports, index + 1);
});
};
window.setTimeout(function () {
var url = connection.url + "/negotiate";
connection.log("Negotiating with '" + url + "'.");
$.ajax({
url: url,
global: false,
cache: false,
type: "GET",
data: {},
dataType: connection.ajaxDataType,
error: function (error) {
$(connection).trigger(events.onError, [error.responseText]);
deferred.reject("SignalR: Error during negotiation request: " + error);
// Stop the connection if negotiate failed
connection.stop();
},
success: function (res) {
connection.appRelativeUrl = res.Url;
connection.id = res.ConnectionId;
connection.webSocketServerUrl = res.WebSocketServerUrl;
if (!res.ProtocolVersion || res.ProtocolVersion !== "1.0") {
$(connection).trigger(events.onError, "SignalR: Incompatible protocol version.");
deferred.reject("SignalR: Incompatible protocol version.");
return;
}
$(connection).trigger(events.onStarting);
var transports = [],
supportedTransports = [];
$.each(signalR.transports, function (key) {
if (key === "webSockets" && !res.TryWebSockets) {
// Server said don't even try WebSockets, but keep processing the loop
return true;
}
supportedTransports.push(key);
});
if ($.isArray(config.transport)) {
// ordered list provided
$.each(config.transport, function () {
var transport = this;
if ($.type(transport) === "object" || ($.type(transport) === "string" && $.inArray("" + transport, supportedTransports) >= 0)) {
transports.push($.type(transport) === "string" ? "" + transport : transport);
}
});
} else if ($.type(config.transport) === "object" ||
$.inArray(config.transport, supportedTransports) >= 0) {
// specific transport provided, as object or a named transport, e.g. "longPolling"
transports.push(config.transport);
} else { // default "auto"
transports = supportedTransports;
}
initialize(transports);
}
});
}, 0);
return deferred.promise();
},
starting: function (callback) {
/// <summary>Adds a callback that will be invoked before the connection is started</summary>
/// <param name="callback" type="Function">A callback function to execute when the connection is starting</param>
/// <returns type="signalR" />
var connection = this,
$connection = $(connection);
$connection.bind(events.onStarting, function (e, data) {
callback.call(connection);
// Unbind immediately, we don't want to call this callback again
$connection.unbind(events.onStarting);
});
return connection;
},
send: function (data) {
/// <summary>Sends data over the connection</summary>
/// <param name="data" type="String">The data to send over the connection</param>
/// <returns type="signalR" />
var connection = this;
if (!connection.transport) {
// Connection hasn't been started yet
throw "SignalR: Connection must be started before data can be sent. Call .start() before .send()";
}
connection.transport.send(connection, data);
// REVIEW: Should we return deferred here?
return connection;
},
sending: function (callback) {
/// <summary>Adds a callback that will be invoked before anything is sent over the connection</summary>
/// <param name="callback" type="Function">A callback function to execute before each time data is sent on the connection</param>
/// <returns type="signalR" />
var connection = this;
$(connection).bind(events.onSending, function (e, data) {
callback.call(connection);
});
return connection;
},
received: function (callback) {
/// <summary>Adds a callback that will be invoked after anything is received over the connection</summary>
/// <param name="callback" type="Function">A callback function to execute when any data is received on the connection</param>
/// <returns type="signalR" />
var connection = this;
$(connection).bind(events.onReceived, function (e, data) {
callback.call(connection, data);
});
return connection;
},
stateChanged: function (callback) {
/// <summary>Adds a callback that will be invoked when the connection state changes</summary>
/// <param name="callback" type="Function">A callback function to execute when the connection state changes</param>
/// <returns type="signalR" />
var connection = this;
$(connection).bind(events.onStateChanged, function (e, data) {
callback.call(connection, data);
});
return connection;
},
error: function (callback) {
/// <summary>Adds a callback that will be invoked after an error occurs with the connection</summary>
/// <param name="callback" type="Function">A callback function to execute when an error occurs on the connection</param>
/// <returns type="signalR" />
var connection = this;
$(connection).bind(events.onError, function (e, data) {
callback.call(connection, data);
});
return connection;
},
disconnected: function (callback) {
/// <summary>Adds a callback that will be invoked when the client disconnects</summary>
/// <param name="callback" type="Function">A callback function to execute when the connection is broken</param>
/// <returns type="signalR" />
var connection = this;
$(connection).bind(events.onDisconnect, function (e, data) {
callback.call(connection);
});
return connection;
},
reconnected: function (callback) {
/// <summary>Adds a callback that will be invoked when the underlying transport reconnects</summary>
/// <param name="callback" type="Function">A callback function to execute when the connection is restored</param>
/// <returns type="signalR" />
var connection = this;
$(connection).bind(events.onReconnect, function (e, data) {
callback.call(connection);
});
return connection;
},
stop: function (async) {
/// <summary>Stops listening</summary>
/// <returns type="signalR" />
var connection = this;
if (connection.state === signalR.connectionState.disconnecting ||
connection.state === signalR.connectionState.disconnected) {
return;
}
try {
changeState(connection, signalR.connectionState.disconnecting);
if (connection.transport) {
connection.transport.abort(connection, async);
connection.transport.stop(connection);
connection.transport = null;
}
// Trigger the disconnect event
$(connection).trigger(events.onDisconnect);
delete connection.messageId;
delete connection.groups;
}
finally {
changeState(connection, signalR.connectionState.disconnected);
}
return connection;
},
log: function (msg) {
log(msg, this.logging);
}
};
signalR.fn.init.prototype = signalR.fn;
// Transports
var transportLogic = {
addQs: function (url, connection) {
if (!connection.qs) {
return url;
}
if (typeof (connection.qs) === "object") {
return url + "&" + $.param(connection.qs);
}
if (typeof (connection.qs) === "string") {
return url + "&" + connection.qs;
}
return url + "&" + window.escape(connection.qs.toString());
},
getUrl: function (connection, transport, reconnecting, appendReconnectUrl) {
/// <summary>Gets the url for making a GET based connect request</summary>
var baseUrl = transport === "webSockets" ? "" : connection.baseUrl,
url = baseUrl + connection.appRelativeUrl,
qs = "transport=" + transport + "&connectionId=" + window.escape(connection.id);
if (connection.data) {
qs += "&connectionData=" + window.escape(connection.data);
}
if (!reconnecting) {
url = url + "/connect";
} else {
if (appendReconnectUrl) {
url = url + "/reconnect";
}
if (connection.messageId) {
qs += "&messageId=" + connection.messageId;
}
if (connection.groups) {
qs += "&groups=" + window.escape(JSON.stringify(connection.groups));
}
}
url += "?" + qs;
url = this.addQs(url, connection);
return url;
},
ajaxSend: function (connection, data) {
var url = connection.url + "/send" + "?transport=" + connection.transport.name + "&connectionId=" + window.escape(connection.id);
url = this.addQs(url, connection);
$.ajax({
url: url,
global: false,
type: "POST",
dataType: connection.ajaxDataType,
data: {
data: data
},
success: function (result) {
if (result) {
$(connection).trigger(events.onReceived, [result]);
}
},
error: function (errData, textStatus) {
if (textStatus === "abort" ||
(textStatus === "parsererror" && connection.ajaxDataType === "jsonp")) {
// The parsererror happens for sends that don't return any data, and hence
// don't write the jsonp callback to the response. This is harder to fix on the server
// so just hack around it on the client for now.
return;
}
$(connection).trigger(events.onError, [errData]);
}
});
},
ajaxAbort: function (connection, async) {
if (typeof (connection.transport) === "undefined") {
return;
}
// Async by default unless explicitly overidden
async = typeof async === "undefined" ? true : async;
var url = connection.url + "/abort" + "?transport=" + connection.transport.name + "&connectionId=" + window.escape(connection.id);
url = this.addQs(url, connection);
$.ajax({
url: url,
async: async,
timeout: 1000,
global: false,
type: "POST",
dataType: connection.ajaxDataType,
data: {}
});
connection.log("Fired ajax abort async = " + async);
},
processMessages: function (connection, data) {
var $connection = $(connection);
if (!data) {
return;
}
if (data.Disconnect) {
connection.log("Disconnect command received from server");
// Disconnected by the server
connection.stop();
return;
}
if (data.Messages) {
$.each(data.Messages, function () {
try {
$connection.trigger(events.onReceived, [this]);
}
catch (e) {
connection.log("Error raising received " + e);
$(connection).trigger(events.onError, [e]);
}
});
}
if (data.MessageId) {
connection.messageId = data.MessageId;
}
if (data.TransportData) {
connection.groups = data.TransportData.Groups;
}
},
foreverFrame: {
count: 0,
connections: {}
}
};
signalR.transports = {
webSockets: {
name: "webSockets",
send: function (connection, data) {
connection.socket.send(data);
},
start: function (connection, onSuccess, onFailed) {
var url,
opened = false,
that = this,
reconnecting = !onSuccess,
protocol;
if (window.MozWebSocket) {
window.WebSocket = window.MozWebSocket;
}
if (!window.WebSocket) {
onFailed();
return;
}
if (!connection.socket) {
if (connection.webSocketServerUrl) {
url = connection.webSocketServerUrl;
}
else {
// Determine the protocol
var info = document.location;
if (info.protocol !== "http:" && info.protocol !== "https:") {
// If the url isn't isn't http or https, use the specified url instead of
// the document url.
var info = window.document.createElement('a');
info.href = connection.url;
}
protocol = info.protocol === "https:" ? "wss://" : "ws://";
url = protocol + info.host;
}
// Build the url
$(connection).trigger(events.onSending);
url += transportLogic.getUrl(connection, this.name, reconnecting);
connection.log("Connecting to websocket endpoint '" + url + "'");
connection.socket = new window.WebSocket(url);
connection.socket.onopen = function () {
opened = true;
connection.log("Websocket opened");
if (onSuccess) {
onSuccess();
}
else {
changeState(connection, signalR.connectionState.connected);
}
};
connection.socket.onclose = function (event) {
if (!opened) {
if (onFailed) {
onFailed();
}
return;
}
else if (typeof event.wasClean !== "undefined" && event.wasClean === false) {
// Ideally this would use the websocket.onerror handler (rather than checking wasClean in onclose) but
// I found in some circumstances Chrome won't call onerror. This implementation seems to work on all browsers.
$(connection).trigger(events.onError, [event.reason]);
connection.log("Unclean disconnect from websocket." + event.reason);
}
else {
connection.log("Websocket closed");
}
changeState(connection, signalR.connectionState.reconnecting);
that.stop(connection);
that.start(connection);
};
connection.socket.onmessage = function (event) {
var data = window.JSON.parse(event.data),
$connection;
if (data) {
$connection = $(connection);
if (data.Messages) {
transportLogic.processMessages(connection, data);
} else {
$connection.trigger(events.onReceived, [data]);
}
}
};
}
},
stop: function (connection) {
if (connection.socket !== null) {
connection.socket.close();
connection.socket = null;
}
},
abort: function (connection) {
}
},
serverSentEvents: {
name: "serverSentEvents",
timeOut: 3000,
start: function (connection, onSuccess, onFailed) {
var that = this,
opened = false,
$connection = $(connection),
reconnecting = !onSuccess,
url,
connectTimeOut;
if (connection.eventSource) {
connection.log("The connection already has an event source. Stopping it.");
connection.stop();
}
if (!window.EventSource) {
if (onFailed) {
connection.log("This browser doesn't support SSE.");
onFailed();
}
return;
}
$connection.trigger(events.onSending);
url = transportLogic.getUrl(connection, this.name, reconnecting);
try {
connection.log("Attempting to connect to SSE endpoint '" + url + "'");
connection.eventSource = new window.EventSource(url);
}
catch (e) {
connection.log("EventSource failed trying to connect with error " + e.Message);
if (onFailed) {
// The connection failed, call the failed callback
onFailed();
}
else {
$connection.trigger(events.onError, [e]);
if (reconnecting) {
// If we were reconnecting, rather than doing initial connect, then try reconnect again
connection.log("EventSource reconnecting");
if (isDisconnecting(connection) === false) {
that.reconnect(connection);
}
}
}
return;
}
// After connecting, if after the specified timeout there's no response stop the connection
// and raise on failed
connectTimeOut = window.setTimeout(function () {
if (opened === false) {
connection.log("EventSource timed out trying to connect");
connection.log("EventSource readyState: " + connection.eventSource.readyState);
if (onFailed) {
onFailed();
}
if (reconnecting) {
// If we're reconnecting and the event source is attempting to connect,
// don't keep retrying. This causes duplicate connections to spawn.
if (connection.eventSource.readyState !== window.EventSource.CONNECTING &&
connection.eventSource.readyState !== window.EventSource.OPEN) {
// If we were reconnecting, rather than doing initial connect, then try reconnect again
connection.log("EventSource reconnecting");
that.reconnect(connection);
}
} else {
connection.log("EventSource stopping the connection.");
that.stop(connection);
}
}
},
that.timeOut);
connection.eventSource.addEventListener("open", function (e) {
connection.log("EventSource connected");
if (connectTimeOut) {
window.clearTimeout(connectTimeOut);
}
if (opened === false) {
opened = true;
if (onSuccess) {
onSuccess();
}
if (reconnecting) {
$connection.trigger(events.onReconnect);
changeState(connection, signalR.connectionState.connected);
}
}
}, false);
connection.eventSource.addEventListener("message", function (e) {
// process messages
if (e.data === "initialized") {
return;
}
transportLogic.processMessages(connection, window.JSON.parse(e.data));
}, false);
connection.eventSource.addEventListener("error", function (e) {
if (!opened) {
if (onFailed) {
onFailed();
}
return;
}
connection.log("EventSource readyState: " + connection.eventSource.readyState);
if (e.eventPhase === window.EventSource.CLOSED) {
// We don't use the EventSource's native reconnect function as it
// doesn't allow us to change the URL when reconnecting. We need
// to change the URL to not include the /connect suffix, and pass
// the last message id we received.
connection.log("EventSource reconnecting due to the server connection ending");
changeState(connection, signalR.connectionState.reconnecting);
if (isDisconnecting(connection) === false) {
that.reconnect(connection);
}
} else {
// connection error
connection.log("EventSource error");
$connection.trigger(events.onError);
}
}, false);
},
reconnect: function (connection) {
var that = this;
window.setTimeout(function () {
that.stop(connection);
that.start(connection);
}, connection.reconnectDelay);
},
send: function (connection, data) {
transportLogic.ajaxSend(connection, data);
},
stop: function (connection) {
if (connection && connection.eventSource) {
connection.eventSource.close();
connection.eventSource = null;
delete connection.eventSource;
}
},
abort: function (connection, async) {
transportLogic.ajaxAbort(connection, async);
}
},
foreverFrame: {
name: "foreverFrame",
timeOut: 3000,
start: function (connection, onSuccess, onFailed) {
var that = this,
frameId = (transportLogic.foreverFrame.count += 1),
url,
connectTimeOut,
frame = $("<iframe data-signalr-connection-id='" + connection.id + "' style='position:absolute;top:0;left:0;width:0;height:0;visibility:hidden;'></iframe>");
if (window.EventSource) {
// If the browser supports SSE, don't use Forever Frame
if (onFailed) {
connection.log("This brower supports SSE, skipping Forever Frame.");
onFailed();
}
return;
}
$(connection).trigger(events.onSending);
// Build the url
url = transportLogic.getUrl(connection, this.name);
url += "&frameId=" + frameId;
frame.prop("src", url);
transportLogic.foreverFrame.connections[frameId] = connection;
connection.log("Binding to iframe's readystatechange event.");
frame.bind("readystatechange", function () {
if ($.inArray(this.readyState, ["loaded", "complete"]) >= 0) {
connection.log("Forever frame iframe readyState changed to " + this.readyState + ", reconnecting");
if (isDisconnecting(connection) === false) {
changeState(connection, signalR.connectionState.reconnecting);
that.reconnect(connection);
}
}
});
connection.frame = frame[0];
connection.frameId = frameId;
if (onSuccess) {
connection.onSuccess = onSuccess;
}
$("body").append(frame);
// After connecting, if after the specified timeout there's no response stop the connection
// and raise on failed
// REVIEW: Why is connectTimeOut set here and never used again?
connectTimeOut = window.setTimeout(function () {
if (connection.onSuccess) {
connection.log("Failed to connect using forever frame source, it timed out after " + that.timeOut + "ms.");
that.stop(connection);
if (onFailed) {
onFailed();
}
}
}, that.timeOut);
},
reconnect: function (connection) {
var that = this;
window.setTimeout(function () {
if (!connection.frame) {
return;
}
var frame = connection.frame,
src = transportLogic.getUrl(connection, that.name, true) + "&frameId=" + connection.frameId;
connection.log("Upating iframe src to '" + src + "'.");
frame.src = src;
}, connection.reconnectDelay);
},
send: function (connection, data) {
transportLogic.ajaxSend(connection, data);
},
receive: function (connection, data) {
var cw;
transportLogic.processMessages(connection, data);
// Delete the script & div elements
connection.frameMessageCount = (connection.frameMessageCount || 0) + 1;
if (connection.frameMessageCount > 50) {
connection.frameMessageCount = 0;
cw = connection.frame.contentWindow || connection.frame.contentDocument;
if (cw && cw.document) {
$("body", cw.document).empty();
}
}
},
stop: function (connection) {
var cw = null;
if (connection.frame) {
if (connection.frame.stop) {
connection.frame.stop();
} else {
cw = connection.frame.contentWindow || connection.frame.contentDocument;
if (cw.document && cw.document.execCommand) {
cw.document.execCommand("Stop");
}
}
$(connection.frame).remove();
delete transportLogic.foreverFrame.connections[connection.frameId];
connection.frame = null;
connection.frameId = null;
delete connection.frame;
delete connection.frameId;
connection.log("Stopping forever frame");
}
},
abort: function (connection, async) {
transportLogic.ajaxAbort(connection, async);
},
getConnection: function (id) {
return transportLogic.foreverFrame.connections[id];
},
started: function (connection) {
if (connection.onSuccess) {
connection.onSuccess();
connection.onSuccess = null;
delete connection.onSuccess;
}
else {
// If there's no onSuccess handler we assume this is a reconnect
$(connection).trigger(events.onReconnect);
changeState(connection, signalR.connectionState.connected);
}
}
},
longPolling: {
name: "longPolling",
reconnectDelay: 3000,
start: function (connection, onSuccess, onFailed) {
/// <summary>Starts the long polling connection</summary>