forked from tidoust/slidyremote
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpresentation-api-shim.js
1818 lines (1585 loc) · 57.4 KB
/
presentation-api-shim.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
/**
* @fileOverview Shim for the latest version of the Presentation API [1] that
* aims to support projecting to Chromecast devices, to attached devices (HDMI,
* Miracast, etc.) through the experimental Chromium build [2] and to a separate
* browser window as a fallback.
*
* Support for Chromecast devices is heavily restrained because Cast receiver
* applications need to be registered with Google before they may be used and
* this code needs to know about the mapping between the URL of the application
* and the application ID provided by Google upon registration.
*
* As such, applications that want to make use of the shim on Google Cast
* devices need first to issue a call to:
* navigator.presentation.registerCastApplication(appUrl, appId)
*
* Other restrictions:
* - the code uses Promises, underlying Web browser needs to support them
* - support for custom events is fairly limited. Only the "on" properties
* are supported to attach to events on exposed objects, no way to use
* "addEventListener" for the time being.
* - The Cast sender library [3] needs to be loaded before that code if one
* wants to support Chromecast devices.
* - the code does not properly handle cases where the receiver calls
* "connection.close()".
*
* The code below is divided in 4 parts:
* a) a few helper functions and the definition of base classes to be used
* by the different presentation mechanisms that are supported
* b) the definition of the CastPresentationMechanism class that allows the
* polyfill to interact with Chromecast devices through the Chrome extension
* c) the definition of the WindowPresentationMechanism class that allows the
* polyfill to create presentations in a new window
* d) the actual definition of "navigator.presentation" and of the other
* related classes
* The different interfaces could be moved to their own JS file, modules are
* not used here not to have to introduce dependencies to some module loader
* library.
*
* References:
* [1] http://webscreens.github.io/presentation-api/
* [2] http://webscreens.github.io/demo/#binaries
* [3] https://www.gstatic.com/cv/js/sender/v1/cast_sender.js
*/
(function () {
/**********************************************************************
Simple console logger to help with debugging. Caller may change logging
level by setting navigator.presentationLogLevel to one of "log", "info",
"warn", "error" or "none" (or null which also means "none").
Note this should be done before that shim is loaded!
**********************************************************************/
var log = function () {
var presentationLogLevel = navigator.presentationLogLevel || 'none';
if ((presentationLogLevel === 'none') || (arguments.length === 0)) {
return;
}
var level = arguments[0];
var params = null;
if ((level === 'log') ||
(level === 'info') ||
(level === 'warn') ||
(level === 'error')) {
// First parameter is the log level
params = Array.prototype.slice.call(arguments, 1);
}
else {
// No log level provided, assume "log"
level = 'log';
params = Array.prototype.slice.call(arguments);
}
if ((level === 'error') ||
((level === 'warn') &&
(presentationLogLevel !== 'error')) ||
((level === 'info') &&
(presentationLogLevel !== 'error') &&
(presentationLogLevel !== 'warn')) ||
((level === 'log') &&
(presentationLogLevel === 'log'))) {
console[level].apply(console, params);
}
};
/**********************************************************************
Short helper function to "queue a task"
**********************************************************************/
var queueTask = function (task) {
setTimeout(task, 0);
};
/**********************************************************************
Shim for DOMExceptions (cannot be instantiated in most browsers for
the time being)
**********************************************************************/
var _DOMException = function (name, message) {
this.name = name;
this.message = message;
};
/**********************************************************************
Global sets of objects that the User Agent must keep track of
**********************************************************************/
/**
* The list of presentation API mechanisms that may be used to connect
* to a second screen
*
* @type {Array(PresentationMechanism)}
*/
var registeredMechanisms = [];
/**
* Register a new presentation API mechanism
*
* @function
* @private
* @param {PresentationMechanism} mechanism The mechanism to register
*/
var registerPresentationMechanism = function (mechanism) {
registeredMechanisms.push(mechanism);
};
/**********************************************************************
DataChannel / RemoteController / RemoteDisplay internal interfaces
**********************************************************************/
/**
* Base class for objects that can send and receive messages
*
* @constructor
* @private
*/
var DataChannel = function () {
var that = this;
/**
* The current connection state
*
* @type {String}
*/
this.state = 'closed';
/**
* Sends a message through the communication channel.
*
* @function
* @param {*} message
*/
this.send = function (message) {
if (that.state !== 'connected') {
throw new _DOMException('InvalidStateError');
}
};
/**
* Event handler called when a message is received on the communication
* channel.
*
* @type {EventHandler}
*/
this.onmessage = null;
/**
* Close the communication channel
*
* @function
*/
this.close = function () {
if (that.state !== 'connected') {
return;
}
that.state = 'closed';
if (that.onstatechange) {
that.onstatechange();
}
};
};
/**
* A remote controller represents a controlling browsing context as seen
* from the receiving browsing context.
*
* This base class is an empty shell. Presentation mechanisms should provide
* their own RemoteController interface that inherits from this one and
* retrieves the right data channel.
*
* @constructor
* @private
* @param {String} name A human-friendly name to identify the context
*/
var RemoteController = function () {
/**
* The underlying data channel used to communicate with the display
*
* @type {DataChannel}
* @private
*/
var channel = null;
/**
* Retrieve the data channel with the remote browsing context
*
* Note the shim only calls that function once (or rather each time the
* data channel needs to be re-created), so no need to worry about
* returning the same Promise if the function is called multiple times.
*
* @function
* @return {Promise<DataChannel>} The promise to get a data communication
* channel ready for exchanging messages with the remote controller
*/
this.createDataChannel = function () {
return new Promise(function (resolve, reject) {
if (!channel) {
channel = new DataChannel();
channel.state = 'connected';
}
resolve(channel);
});
};
};
/**
* Represents a display (or a class of displays in this implementation) as
* seen from the controlling browsing context. The display may be navigated
* to a given URL, in which case it can also be used to send messages to the
* receiving browsing context or receive messages from it.
*
* @constructor
* @private
* @param {String} name A human-friendly name to identify the context
*/
var Display = function (name) {
/**
* A human-friendly name for the display
*
* @type {String}
*/
this.name = name;
/**
* Navigate the display to the given URL, thus creating a receiving
* browsing context.
*
* @function
* @param {String} url The URL to navigate to
* @return {Promise} The promise to have navigated to the given URL. The
* promise is rejected with a DOMException named "OperationError"
*/
this.navigate = function (url) {
return new Promise(function (resolve, reject) {
reject(new _DOMException('OperationError'));
});
};
/**
* Create a data channel with the remote browsing context
*
* Note the shim only calls that function once (or rather each time the
* data channel needs to be re-created), so no need to worry about
* returning the same Promise if the function is called multiple times.
*
* @function
* @return {Promise<DataChannel>} The promise to get a data communication
* channel ready for exchanging messages with the remote controller
*/
this.createDataChannel = function () {
return new Promise(function (resolve, reject) {
if (!channel) {
channel = new DataChannel();
channel.state = 'connected';
}
resolve(channel);
});
};
/**
* Terminates the presentation with the display
*/
this.terminate = function () {};
};
/**********************************************************************
PresentationMechanism internal interface
**********************************************************************/
/**
* Exposes a mechanism to detect, connect and control a second screen
*
* Concrete mechanisms must inherit from this base class.
*
* @constructor
* @private
*/
var PresentationMechanism = function () {
/**
* Some friendly name for the mechanism, mostly for logging purpose
*
* To be set in derivated classes.
*
* @type {String}
*/
this.name = 'default presentation mechanism';
/**
* Compute the list of available presentation displays that the user may
* select to launch a presentation.
*
* @function
* @return {Promise<Array(Display)} The promise to get the current list of
* available presentation displays
*/
this.getAvailableDisplays = function () {
return new Promise(function (resolve, reject) {
resolve([]);
});
};
/**
* Start to monitor incoming presentation connections if code runs on the
* receiving side.
*
* The function should not do anything if the code is not running on the
* receiving side.
*
* @function
*/
this.monitorIncomingControllers = function () {
queueTask(function () {
});
};
/**
* Event handler called when an incoming controller is detected
*
* The "controller" attribute of the event that is given to the handler is set
* to the remote controller that connected to this browsing context
*
* @type {EventHandler}
*/
this.onincomingcontroller = null;
};
/**********************************************************************
CastPresentationMechanism
**********************************************************************/
/**
* The cast presentation mechanism allows a user to request display of
* Web content on available Google Cast devices discovered through the
* Cast extension.
*
* The extension does not expose the list of Chromecast devices that
* are available, so this mechanism takes for granted that there is
* one.
*
* Note that the mechanism also exposes the "registerCastApplication"
* static function to register the mapping between a receiver app URL
* and its Google Cast ID
*
* @constructor
* @inherits {PresentationMechanism}
*/
var CastPresentationMechanism = (function () {
/**
* Whether the Cast API library is available or not.
* If it's not, the Promises returned by "create" and "startReceiver"
* will always end up being rejected.
*/
var castApiAvailable = false;
window['__onGCastApiAvailable'] = function (loaded, errorInfo) {
if (loaded) {
log('Google Cast API library is available and loaded');
castApiAvailable = true;
} else {
log('warn',
'Google Cast API library is available but could not be loaded',
errorInfo);
}
};
/**
* Whether the Cast API library has been initialized.
*
* That flag is used to support multiple calls to "requestSession". Once
* the Cast API library has been initialized, subsequent Cast session
* requests should directly call sessionRequest.
*/
var castApiInitialized = false;
/**
* Mapping table between receiver application URLs and Cast application IDs
*
* Ideally, there should not be any need to maintain such a mapping table
* but there is no way to have an arbitrary URL run on a Chromecast device.
*/
var castApplications = {};
/**
* Remote controller from the perspective of the Cast device
*
* @constructor
* @inherits {RemoteController}
* @param {cast.ReceiverManager} castReceiverManager The cast's receiver
* manager.
*/
var CastRemoteController = function (castReceiverManager) {
RemoteController.call(this);
var customMessageBus = castReceiverManager.getCastMessageBus(
'urn:x-cast:org.w3c.webscreens.presentationapi.shim',
cast.receiver.CastMessageBus.MessageType.JSON);
this.createDataChannel = function () {
return new Promise(function (resolve, reject) {
var channel = new DataChannel();
channel.state = 'connected';
customMessageBus.addEventListener('message', function (event) {
log('received message from Cast sender', event.data);
if (channel.onmessage) {
channel.onmessage(event);
}
});
channel.send = function (message) {
if (channel.state !== 'connected') {
throw new _DOMException('InvalidStateError');
}
log('send message to Cast sender', message);
customMessageBus.broadcast(message);
};
channel.close = function () {
if (channel.state !== 'connected') {
return;
}
channel.state = 'closed';
if (channel.onstatechange) {
channel.onstatechange();
}
};
resolve(channel);
});
};
this.terminate = function () {
log('stop Cast receiver manager');
castReceiverManager.stop();
};
};
/**
* Represents a Chromecast device that may be navigated to a URL
*
* The class more accurately represents the possibility that the user
* will have a Chromecast device at hand that could be used to browse
* the requested URL. The actual device is not known a priori.
*
* @function
* @inherits {Display}
* @param {String} name A human-friendly name for the "device"
*/
var CastDisplay = function (name) {
Display.call(this, name);
this.state = 'closed';
var castSession = null;
this.navigate = function (url) {
return new Promise(function (resolve, reject) {
if (!castApiAvailable) {
log('cannot create Cast session',
'Google Cast API library is not available');
reject(new _DOMException('OperationError'));
return;
}
if (!castApplications[url]) {
log('cannot create Cast session',
'no receiver app known for url', url);
reject(new _DOMException('OperationError'));
return;
}
var applicationId = castApplications[url];
var sessionRequest = new chrome.cast.SessionRequest(applicationId);
var requestSession = function () {
log('request new Cast session for url', url);
chrome.cast.requestSession(function (session) {
log('got a new Cast session');
castSession = session;
resolve();
}, function (error) {
if (castSession) {
return;
}
if (error.code === 'cancel') {
log('info', 'user chose not to use Cast device');
}
else if (error.code === 'receiver_unavailable') {
log('info', 'no compatible Cast device found');
}
else {
log('error', 'could not create Cast session', error);
}
reject(new _DOMException('OperationError'));
}, sessionRequest);
};
var apiConfig = new chrome.cast.ApiConfig(
sessionRequest,
function sessionListener(session) {
// Method called at most once after initialization if a running
// Cast session may be resumed
log('found existing Cast session, reusing');
castSession = session;
resolve();
},
function receiverListener(available) {
// Method called whenever the number of Cast devices available in
// the local network changes. The method is called at least once
// after initialization. We're interested in that first call.
if (castSession) {
return;
}
// Reject creation if there are no Google Cast devices that
// can handle the application.
if (available !== chrome.cast.ReceiverAvailability.AVAILABLE) {
log('cannot create Cast session',
'no Cast device available for url', url);
reject(new _DOMException('OperationError'));
}
log('found at least one compatible Cast device');
requestSession();
});
if (castApiInitialized) {
// The Cast API library has already been initialized, call
// requestSession directly.
log('Google Cast API library already initialized',
'request new Cast session');
requestSession();
}
else {
// The Cast API library first needs to be initialized
log('initialize Google Cast API library for url', url);
chrome.cast.initialize(apiConfig, function () {
// Note actual session creation is handled by callback functions
// defined above
log('Google Cast API library initialized');
castApiInitialized = true;
}, function (err) {
log('error',
'Google Cast API library could not be initialized', err);
reject();
return;
});
}
});
};
this.createDataChannel = function () {
return new Promise(function (resolve, reject) {
if (!castSession) {
reject();
return;
}
var channel = new DataChannel();
channel.state = 'connected';
var updateListener = function () {
channel.state = (castSession === chrome.cast.SessionStatus.CONNECTED) ?
'connected' : 'closed';
log('received Cast session state update', 'isAlive=' + isAlive);
if (channel.onstatechange) {
channel.onstatechange();
}
if (channel.state !== 'connected') {
castSession.removeMessageListener(messageListener);
castSession.removeUpdateListener(updateListener);
}
};
var messageListener = function (namespace, message) {
log('received message from Cast receiver', message);
if (channel.onmessage) {
channel.onmessage({ data: message });
}
};
var namespace = castSession.namespaces[0];
castSession.addUpdateListener(updateListener);
castSession.addMessageListener(namespace.name, messageListener);
channel.send = function (message) {
if (channel.state !== 'connected') {
throw new _DOMException('InvalidStateError');
}
log('send message to Cast receiver', message);
var namespace = castSession.namespaces[0];
castSession.sendMessage(namespace.name, message);
};
channel.close = function () {
if (channel.state !== 'connected') {
return;
}
castSession.removeMessageListener(messageListener);
castSession.removeUpdateListener(updateListener);
channel.state = 'closed';
if (channel.onstatechange) {
channel.onstatechange();
}
};
resolve(channel);
});
};
this.terminate = function () {
log('close Cast session');
castSession.stop();
};
};
/**
* The actual presentation mechanism based on the Chrome Cast extension
*/
var CastPresentationMechanism = function () {
PresentationMechanism.call(this);
this.name = 'cast presentation mechanism';
var that = this;
this.getAvailableDisplays = function () {
return new Promise(function (resolve, reject) {
if (castApiAvailable) {
resolve([new CastDisplay('A chromecast device')]);
}
else {
resolve([]);
}
});
};
this.monitorIncomingControllers = function () {
// Detect whether the code is running on a Google Cast device. If it is,
// it means the code is used within a Receiver application and was
// launched as the result of a call to:
// navigator.presentation.requestSession
// NB: no better way to tell whether we're running on a Cast device
// for the time being, see:
// https://code.google.com/p/google-cast-sdk/issues/detail?id=157
var runningOnChromecast = !!window.navigator.userAgent.match(/CrKey/);
if (!runningOnChromecast) {
log('code is not running on a Google Cast device');
return;
}
// Start the Google Cast receiver
// Note the need to create the CastReceiverSession before the call to
// "start", as that class registers the namespace used for the
// communication channel.
log('code is running on a Google Cast device',
'start Google Cast receiver manager');
var castReceiverManager = cast.receiver.CastReceiverManager.getInstance();
var controller = new CastRemoteController(castReceiverManager);
castReceiverManager.start();
castReceiverManager.onReady = function () {
log('Google Cast receiver manager started');
if (that.onincomingcontroller) {
that.onincomingcontroller(controller);
}
};
};
};
/**
* Registers the equivalence between the URL of a receiver application and
* its Google Cast app ID.
*
* @function
* @static
* @param {String} url URL of the receiver application
* @param {String} id The Cast application ID associated with that URL
*/
CastPresentationMechanism.registerCastApplication = function (url, id) {
castApplications[url] = id;
};
// Expose the presentation mechanism to the external world
return CastPresentationMechanism;
})();
/**********************************************************************
WindowPresentationMechanism
**********************************************************************/
/**
* The window presentation mechanism allows a user to open a new window on
* the same screen and pretend that it is a second screen.
*
* @constructor
* @inherits {PresentationMechanism}
*/
var WindowPresentationMechanism = (function () {
/**
* Remote window controller
*
* @constructor
* @private
* @inherits {RemoteController}
* @param {Window} source Reference to the controlling window
*/
var WindowRemoteController = function (source) {
RemoteController.call(this);
this.createDataChannel = function () {
return new Promise(function (resolve, reject) {
var channel = new DataChannel();
var initMessageListener = function (event) {
if ((event.source === source) &&
(event.data === 'channel')) {
log('received message to start data channel');
channel.state = 'connected';
window.removeEventListener('message', initMessageListener);
window.addEventListener('message', messageListener);
source.postMessage('channelready', '*');
resolve(channel);
}
};
window.addEventListener('message', initMessageListener);
var messageListener = function (event) {
if (event.source === source) {
if (channel.onmessage) {
channel.onmessage(event);
}
}
};
channel.send = function (message) {
if (channel.state !== 'connected') {
throw new _DOMException('InvalidStateError');
}
log('send message to receiving window', message);
source.postMessage(message, '*');
};
channel.close = function () {
if (channel.state !== 'connected') {
return;
}
window.removeEventListener('message', messageListener);
channel.state = 'closed';
if (channel.onstatechange) {
channel.onstatechange();
}
};
});
};
};
/**
* Remote window display that may be navigated to some URL
*
* @constructor
* @private
* @param {String} name Human-friendly name for that display
*/
var WindowDisplay = function (name) {
Display.call(this, name);
var receivingWindow = null;
var openPromise = null;
var openPromiseResolve = null;
var openPromiseReject = null;
var reconnectionNeeded = false;
var that = this;
this.navigate = function (url) {
return new Promise(function (resolve, reject) {
receivingWindow = window.open(url, name);
if (!receivingWindow) {
log('could not open receiving window');
reject(new _DOMException('OperationError'));
return;
}
var isPresentationListener = function (event) {
if ((event.source === receivingWindow) &&
(event.data === 'ispresentation')) {
log('received "is this a presentation connection?" message ' +
'from receiving window');
log('send "presentation" message to receiving window');
receivingWindow.postMessage('presentation', '*');
window.removeEventListener('message', isPresentationListener);
resolve();
}
};
window.addEventListener('message', isPresentationListener);
});
};
this.createDataChannel = function () {
return new Promise(function (resolve, reject) {
var channel = new DataChannel();
channel.state = 'connected';
var readyMessageListener = function (event) {
if ((event.source === receivingWindow) &&
(event.data === 'channelready')) {
log('received "channel ready" message from receiving window');
channel.state = 'connected';
window.removeEventListener('message', readyMessageListener);
window.addEventListener('message', messageListener);
resolve(channel);
}
};
var messageListener = function (event) {
if ((event.source === receivingWindow) &&
(event.data === 'receivershutdown')) {
log('received shut down message from receiving side', 'disconnect');
channel.state = 'terminated';
if (channel.onstatechange) {
channel.onstatechange();
}
}
else {
log('received message from receiving window', event.data);
if (that.onmessage) {
that.onmessage(event);
}
}
};
log('tell receiving window to create data channel');
receivingWindow.postMessage('channel', '*');
window.addEventListener('message', readyMessageListener);
channel.send = function (message) {
if (channel.state !== 'connected') {
throw new _DOMException('InvalidStateError');
}
log('send message to receiving window', message);
receivingWindow.postMessage(message, '*');
};
channel.close = function () {
if (channel.state !== 'connected') {
return;
}
window.removeEventListener('messsage', messageListener);
channel.state = 'closed';
if (channel.onstatechange) {
channel.onstatechange();
}
};
});
};
this.terminate = function () {
log('close presentation window');
receivingWindow.close();
};
};
var WindowPresentationMechanism = function () {
PresentationMechanism.call(this);
this.name = 'window presentation mechanism';
var controllingWindows = [];
var that = this;
this.getAvailableDisplays = function () {
return new Promise(function (resolve, reject) {
var display = new WindowDisplay('A beautiful window on your screen');
resolve([display]);
});
};
this.monitorIncomingControllers = function () {
// No window opener? The code does not run a receiver app.
if (!window.opener) {
log('code is not running in a receiving window');
return;
}
var messageEventListener = function (event) {
// Note that the event source window is not checked to allow multiple
// controlling windows
if (event.data === 'presentation') {
log('received "presentation" message from some window');
log('code is running in a receiving window');
if (that.onincomingcontroller &&
!controllingWindows.some(function (win) {
return (win === event.source);
})) {
controllingWindows.push(event.source);
var controller = new WindowRemoteController(event.source);
if (that.onincomingcontroller) {
that.onincomingcontroller(controller);
}
}
}
};
window.addEventListener('message', messageEventListener, false);
log('send "ispresentation" message to opener window');
window.opener.postMessage('ispresentation', '*');
window.addEventListener('unload', function () {
log('receiving window is being closed');
controllingWindows.forEach(function (win) {
if (win) {
win.postMessage('receivershutdown', '*');
}
});
}, false);
};
};
WindowPresentationMechanism.prototype = new PresentationMechanism();
// Expose the presentation mechanism to the external world
return WindowPresentationMechanism;
})();
/**********************************************************************
PresentationConnection interface
**********************************************************************/
/**
* Implements the PresentationConnection interface that is merely a wrapper
* around a specified connection.
*
* @constructor
* @param {RemoteController|Display} remotePeer An object that represents the
* remote peer with wich the presentation connection is associated.
*/
var PresentationConnection = function (remotePeer) {
var that = this;
/**
* The presentation connection identifier
*
* @type {String}
*/
this.id = null;
/**
* The current connection state
*