This repository has been archived by the owner on Dec 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
activities.js
2967 lines (2614 loc) · 76.4 KB
/
activities.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
/**
* @license
* Copyright 2017 The Web Activities 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.
*/
/** Version: 1.24 */
'use strict';
/*eslint no-unused-vars: 0*/
/**
* @enum {string}
*/
const ActivityMode = {
IFRAME: 'iframe',
POPUP: 'popup',
REDIRECT: 'redirect',
};
/**
* The result code used for `ActivityResult`.
* @enum {string}
*/
const ActivityResultCode = {
OK: 'ok',
CANCELED: 'canceled',
FAILED: 'failed',
};
/**
* The result of an activity. The activity implementation returns this object
* for a successful result, a cancelation or a failure.
* @struct
*/
class ActivityResult {
/**
* @param {!ActivityResultCode} code
* @param {*} data
* @param {!ActivityMode} mode
* @param {string} origin
* @param {boolean} originVerified
* @param {boolean} secureChannel
*/
constructor(code, data, mode, origin, originVerified, secureChannel) {
/** @const {!ActivityResultCode} */
this.code = code;
/** @const {*} */
this.data = code == ActivityResultCode.OK ? data : null;
/** @const {!ActivityMode} */
this.mode = mode;
/** @const {string} */
this.origin = origin;
/** @const {boolean} */
this.originVerified = originVerified;
/** @const {boolean} */
this.secureChannel = secureChannel;
/** @const {boolean} */
this.ok = code == ActivityResultCode.OK;
/** @const {?Error} */
this.error = code == ActivityResultCode.FAILED ?
new Error(String(data) || '') :
null;
}
}
/**
* The activity request that different types of hosts can be started with.
* @typedef {{
* requestId: string,
* returnUrl: string,
* args: ?Object,
* origin: (string|undefined),
* originVerified: (boolean|undefined),
* }}
*/
let ActivityRequest;
/**
* The activity "open" options used for popups and redirects.
*
* - returnUrl: override the return URL. By default, the current URL will be
* used.
* - skipRequestInUrl: removes the activity request from the URL, in case
* redirect is used. By default, the activity request is appended to the
* activity URL. This option can be used if the activity request is passed
* to the activity by some alternative means.
* - disableRedirectFallback: disallows popup fallback to redirect. By default
* the redirect fallback is allowed. This option has to be used very carefully
* because there are many user agents that may fail to open a popup and it
* won't be always possible for the opener window to even be aware of such
* failures.
*
* @typedef {{
* returnUrl: (string|undefined),
* skipRequestInUrl: (boolean|undefined),
* disableRedirectFallback: (boolean|undefined),
* width: (number|undefined),
* height: (number|undefined),
* }}
*/
let ActivityOpenOptions;
/**
* Activity client-side binding. The port provides limited ways to communicate
* with the activity and receive signals and results from it. Not every type
* of activity exposes a port.
*
* @interface
*/
class ActivityPort {
/**
* Returns the mode of the activity: iframe, popup or redirect.
* @return {!ActivityMode}
*/
getMode() {}
/**
* Accepts the result when ready. The client should verify the activity's
* mode, origin, verification and secure channel flags before deciding
* whether or not to trust the result.
*
* Returns the promise that yields when the activity has been completed and
* either a result, a cancelation or a failure has been returned.
*
* @return {!Promise<!ActivityResult>}
*/
acceptResult() {}
}
/**
* Activity client-side binding for messaging.
*
* Whether the host can or cannot receive a message depends on the type of
* host and its state. Ensure that the code has an alternative path if
* messaging is not available.
*
* @interface
*/
class ActivityMessagingPort {
/**
* Returns the target window where host is loaded. May be unavailable.
* @return {?Window}
*/
getTargetWin() {}
/**
* Sends a message to the host.
* @param {!Object} payload
*/
message(payload) {}
/**
* Registers a callback to receive messages from the host.
* @param {function(!Object)} callback
*/
onMessage(callback) {}
/**
* Creates a new communication channel or returns an existing one.
* @param {string=} opt_name
* @return {!Promise<!MessagePort>}
*/
messageChannel(opt_name) {}
}
/**
* Activity implementation. The host provides interfaces, callbacks and
* signals for the activity's implementation to communicate with the client
* and return the results.
*
* @interface
*/
class ActivityHost {
/**
* Returns the mode of the activity: iframe, popup or redirect.
* @return {!ActivityMode}
*/
getMode() {}
/**
* The request string that the host was started with. This value can be
* passed around while the target host is navigated.
*
* Not always available; in particular, this value is not available for
* iframe hosts.
*
* See `ActivityRequest` for more info.
*
* @return {?string}
*/
getRequestString() {}
/**
* The client's origin. The connection to the client must first succeed
* before the origin can be known with certainty.
* @return {string}
*/
getTargetOrigin() {}
/**
* Whether the client's origin has been verified. This depends on the type of
* the client connection. When window messaging is used (for iframes and
* popups), the origin can be verified. In case of redirects, where state is
* passed in the URL, the verification is not fully possible.
* @return {boolean}
*/
isTargetOriginVerified() {}
/**
* Whether the client/host communication is done via a secure channel such
* as messaging, or an open and easily exploitable channel, such redirect URL.
* Iframes and popups use a secure channel, and the redirect mode does not.
* @return {boolean}
*/
isSecureChannel() {}
/**
* Signals to the host to accept the connection. Before the connection is
* accepted, no other calls can be made, such as `ready()`, `result()`, etc.
*
* Since the result of the activity could be sensitive, the host API requires
* you to verify the connection. The host can use the client's origin,
* verified flag, whether the channel is secure, activity arguments, and other
* properties to confirm whether the connection should be accepted.
*
* The client origin is verifiable in popup and iframe modes, but may not
* be verifiable in the redirect mode. The channel is secure for iframes and
* popups and not secure for redirects.
*/
accept() {}
/**
* The arguments the activity was started with. The connection to the client
* must first succeed before the origin can be known with certainty.
* @return {?Object}
*/
getArgs() {}
/**
* Signals to the opener that the host is ready to be interacted with.
*/
ready() {}
/**
* Whether the supplemental messaging suppored for this host mode. Only iframe
* hosts can currently send and receive messages.
* @return {boolean}
*/
isMessagingSupported() {}
/**
* Sends a message to the client. Notice that only iframe hosts can send and
* receive messages.
* @param {!Object} payload
*/
message(payload) {}
/**
* Registers a callback to receive messages from the client. Notice that only
* iframe hosts can send and receive messages.
* @param {function(!Object)} callback
*/
onMessage(callback) {}
/**
* Creates a new supplemental communication channel or returns an existing
* one. Notice that only iframe hosts can send and receive messages.
* @param {string=} opt_name
* @return {!Promise<!MessagePort>}
*/
messageChannel(opt_name) {}
/**
* Signals to the activity client the result of the activity.
* @param {*} data
*/
result(data) {}
/**
* Signals to the activity client that the activity has been canceled by the
* user.
*/
cancel() {}
/**
* Signals to the activity client that the activity has unrecoverably failed.
* @param {!Error|string} reason
*/
failed(reason) {}
/**
* Set the size container. This element will be used to measure the
* size needed by the iframe. Not required for non-iframe hosts. The
* needed height is calculated as `sizeContainer.scrollHeight`.
* @param {!Element} element
*/
setSizeContainer(element) {}
/**
* Signals to the activity client that the activity's size needs might have
* changed. Not required for non-iframe hosts.
*/
resized() {}
/**
* The callback the activity implementation can implement to react to changes
* in size. Normally, this callback is called in reaction to the `resized()`
* method.
* @param {function(number, number, boolean)} callback
*/
onResizeComplete(callback) {}
/**
* Disconnect the activity implementation and cleanup listeners.
*/
disconnect() {}
}
/** Only allows http/https URLs. */
const HTTP_S_ONLY_RE = /^https?\:/i;
/** DOMException.ABORT_ERR name */
const ABORT_ERR_NAME = 'AbortError';
/** DOMException.ABORT_ERR = 20 */
const ABORT_ERR_CODE = 20;
/** @type {?HTMLAnchorElement} */
let aResolver;
/**
* @param {string} urlString
* @return {!HTMLAnchorElement}
*/
function parseUrl(urlString) {
if (!aResolver) {
aResolver = /** @type {!HTMLAnchorElement} */ (document.createElement('a'));
}
aResolver.href = urlString;
return /** @type {!HTMLAnchorElement} */ (aResolver);
}
/**
* @param {!Location|!URL|!HTMLAnchorElement} loc
* @return {string}
*/
function getOrigin(loc) {
if (loc.origin) {
return loc.origin;
}
// Make sure that the origin is normalized. Specifically on IE, host sometimes
// includes the default port, which is not per standard.
const protocol = loc.protocol;
let host = loc.host;
if (protocol == 'https:' && host.indexOf(':443') == host.length - 4) {
host = host.replace(':443', '');
} else if (protocol == 'http:' && host.indexOf(':80') == host.length - 3) {
host = host.replace(':80', '');
}
return protocol + '//' + host;
}
/**
* @param {string} urlString
* @return {string}
*/
function getOriginFromUrl(urlString) {
return getOrigin(parseUrl(urlString));
}
/**
* @param {!Window} win
* @return {string}
*/
function getWindowOrigin(win) {
return (win.origin || getOrigin(win.location));
}
/**
* @param {string} urlString
* @return {string}
*/
function removeFragment(urlString) {
const index = urlString.indexOf('#');
if (index == -1) {
return urlString;
}
return urlString.substring(0, index);
}
/**
* Parses and builds Object of URL query string.
* @param {string} query The URL query string.
* @return {!Object<string, string>}
*/
function parseQueryString(query) {
if (!query) {
return {};
}
return (/^[?#]/.test(query) ? query.slice(1) : query)
.split('&')
.reduce((params, param) => {
const item = param.split('=');
const key = decodeURIComponent(item[0] || '');
const value = decodeURIComponent(item[1] || '');
if (key) {
params[key] = value;
}
return params;
}, {});
}
/**
* @param {string} queryString A query string in the form of "a=b&c=d". Could
* be optionally prefixed with "?" or "#".
* @param {string} param The param to get from the query string.
* @return {?string}
*/
function getQueryParam(queryString, param) {
return parseQueryString(queryString)[param];
}
/**
* Add a query-like parameter to the fragment string.
* @param {string} url
* @param {string} param
* @param {string} value
* @return {string}
*/
function addFragmentParam(url, param, value) {
return url +
(url.indexOf('#') == -1 ? '#' : '&') +
encodeURIComponent(param) + '=' + encodeURIComponent(value);
}
/**
* @param {string} queryString A query string in the form of "a=b&c=d". Could
* be optionally prefixed with "?" or "#".
* @param {string} param The param to remove from the query string.
* @return {?string}
*/
function removeQueryParam(queryString, param) {
if (!queryString) {
return queryString;
}
const search = encodeURIComponent(param) + '=';
let index = -1;
do {
index = queryString.indexOf(search, index);
if (index != -1) {
const prev = index > 0 ? queryString.substring(index - 1, index) : '';
if (prev == '' || prev == '?' || prev == '#' || prev == '&') {
let end = queryString.indexOf('&', index + 1);
if (end == -1) {
end = queryString.length;
}
queryString =
queryString.substring(0, index) +
queryString.substring(end + 1);
} else {
index++;
}
}
} while (index != -1 && index < queryString.length);
return queryString;
}
/**
* Asserts that a given url is an absolute HTTP or HTTPS URL.
* @param {?string} urlString
* @return {?string}
*/
function assertAbsoluteHttpOrHttpsUrl(urlString) {
if (!HTTP_S_ONLY_RE.test(urlString)) {
throw new Error('must be http(s)');
}
return urlString;
}
/**
* Asserts that a given url is not an obvious script URL. This is not intended
* as a complete verification. The complete verification is left up to the
* host before `accept()` method is called.
* @param {?string} urlString
* @return {?string}
*/
function assertObviousUnsafeUrl(urlString) {
if (urlString) {
if (parseUrl(urlString).protocol.indexOf('script') != -1) {
throw new Error('unsafe "' + urlString + '"');
}
}
return urlString;
}
/**
* @param {?string} requestString
* @param {boolean=} trusted
* @return {?ActivityRequest}
*/
function parseRequest(requestString, trusted = false) {
if (!requestString) {
return null;
}
const parsed = /** @type {!Object} */ (JSON.parse(requestString));
const request = {
requestId: /** @type {string} */ (parsed['requestId']),
returnUrl: /** @type {string} */ (parsed['returnUrl']),
args: /** @type {?Object} */ (parsed['args'] || null),
};
if (trusted) {
request.origin = /** @type {string|undefined} */ (
parsed['origin'] || undefined);
request.originVerified = /** @type {boolean|undefined} */ (
parsed['originVerified'] || undefined);
}
return request;
}
/**
* @param {!ActivityRequest} request
* @return {string}
*/
function serializeRequest(request) {
const map = {
'requestId': request.requestId,
'returnUrl': request.returnUrl,
'args': request.args,
};
if (request.origin !== undefined) {
map['origin'] = request.origin;
}
if (request.originVerified !== undefined) {
map['originVerified'] = request.originVerified;
}
return JSON.stringify(map);
}
/**
* @param {*} error
* @return {boolean}
*/
function isAbortError(error) {
if (!error || typeof error != 'object') {
return false;
}
return (error['name'] === ABORT_ERR_NAME);
}
/**
* Creates or emulates a DOMException of AbortError type.
* See https://heycam.github.io/webidl/#aborterror.
* @param {!Window} win
* @param {string=} opt_message
* @return {!DOMException}
*/
function createAbortError(win, opt_message) {
const message = 'AbortError' + (opt_message ? ': ' + opt_message : '');
let error = null;
if (typeof win['DOMException'] == 'function') {
// TODO(dvoytenko): remove typecast once externs are fixed.
const constr = /** @type {function(new:DOMException, string, string)} */ (
win['DOMException']);
try {
error = new constr(message, ABORT_ERR_NAME);
} catch (e) {
// Ignore. In particular, `new DOMException()` fails in Edge.
}
}
if (!error) {
// TODO(dvoytenko): remove typecast once externs are fixed.
const constr = /** @type {function(new:DOMException, string)} */ (
Error);
error = new constr(message);
error.name = ABORT_ERR_NAME;
error.code = ABORT_ERR_CODE;
}
return error;
}
/**
* Resolves the activity result as a promise:
* - `OK` result is yielded as the promise's payload;
* - `CANCEL` result is rejected with the `AbortError`;
* - `FAILED` result is rejected with the embedded error.
*
* @param {!Window} win
* @param {!ActivityResult} result
* @param {function((!ActivityResult|!Promise))} resolver
*/
function resolveResult(win, result, resolver) {
if (result.ok) {
resolver(result);
} else {
const error = result.error || createAbortError(win);
error.activityResult = result;
resolver(Promise.reject(error));
}
}
/**
* @param {!Window} win
* @return {boolean}
*/
function isIeBrowser(win) {
// MSIE and Trident are typical user agents for IE browsers.
const nav = win.navigator;
return /Trident|MSIE|IEMobile/i.test(nav && nav.userAgent);
}
/**
* @param {!Window} win
* @return {boolean}
*/
function isEdgeBrowser(win) {
const nav = win.navigator;
return /Edge/i.test(nav && nav.userAgent);
}
/**
* @param {!Error} e
*/
function throwAsync(e) {
setTimeout(() => {throw e;});
}
/**
* Polyfill of the `Node.isConnected` API. See
* https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected.
* @param {!Node} node
* @return {boolean}
*/
function isNodeConnected(node) {
// Ensure that node is attached if specified. This check uses a new and
// fast `isConnected` API and thus only checked on platforms that have it.
// See https://www.chromestatus.com/feature/5676110549352448.
if ('isConnected' in node) {
return node['isConnected'];
}
// Polyfill.
const root = node.ownerDocument && node.ownerDocument.documentElement;
return (root && root.contains(node)) || false;
}
const SENTINEL = '__ACTIVITIES__';
/**
* The messenger helper for activity's port and host.
*/
class Messenger {
/**
* @param {!Window} win
* @param {!Window|function():?Window} targetOrCallback
* @param {?string} targetOrigin
* @param {boolean} requireTarget
*/
constructor(win, targetOrCallback, targetOrigin, requireTarget) {
/** @private @const {!Window} */
this.win_ = win;
/** @private @const {!Window|function():?Window} */
this.targetOrCallback_ = targetOrCallback;
/**
* May start as unknown (`null`) until received in the first message.
* @private {?string}
*/
this.targetOrigin_ = targetOrigin;
/** @private @const {boolean} */
this.requireTarget_ = requireTarget;
/** @private {?Window} */
this.target_ = null;
/** @private {boolean} */
this.acceptsChannel_ = false;
/** @private {?MessagePort} */
this.port_ = null;
/** @private {?function(string, ?Object)} */
this.onCommand_ = null;
/** @private {?function(!Object)} */
this.onCustomMessage_ = null;
/**
* @private {?Object<string, !ChannelHolder>}
*/
this.channels_ = null;
/** @private @const */
this.boundHandleEvent_ = this.handleEvent_.bind(this);
}
/**
* Connect the port to the host or vice versa.
* @param {function(string, ?Object)} onCommand
*/
connect(onCommand) {
if (this.onCommand_) {
throw new Error('already connected');
}
this.onCommand_ = onCommand;
this.win_.addEventListener('message', this.boundHandleEvent_);
}
/**
* Disconnect messenger.
*/
disconnect() {
if (this.onCommand_) {
this.onCommand_ = null;
if (this.port_) {
closePort(this.port_);
this.port_ = null;
}
this.win_.removeEventListener('message', this.boundHandleEvent_);
if (this.channels_) {
for (const k in this.channels_) {
const channelObj = this.channels_[k];
if (channelObj.port1) {
closePort(channelObj.port1);
}
if (channelObj.port2) {
closePort(channelObj.port2);
}
}
this.channels_ = null;
}
}
}
/**
* Returns whether the messenger has been connected already.
* @return {boolean}
*/
isConnected() {
return this.targetOrigin_ != null;
}
/**
* Returns the messaging target. Only available when connection has been
* establihsed.
* @return {!Window}
*/
getTarget() {
const target = this.getOptionalTarget_();
if (!target) {
throw new Error('not connected');
}
return target;
}
/**
* @return {?Window}
* @private
*/
getOptionalTarget_() {
if (this.onCommand_ && !this.target_) {
if (typeof this.targetOrCallback_ == 'function') {
this.target_ = this.targetOrCallback_();
} else {
this.target_ = /** @type {!Window} */ (this.targetOrCallback_);
}
}
return this.target_;
}
/**
* Returns the messaging origin. Only available when connection has been
* establihsed.
* @return {string}
*/
getTargetOrigin() {
if (this.targetOrigin_ == null) {
throw new Error('not connected');
}
return this.targetOrigin_;
}
/**
* The host sends this message to the client to indicate that it's ready to
* start communicating. The client is expected to respond back with the
* "start" command. See `sendStartCommand` method.
*/
sendConnectCommand() {
// TODO(dvoytenko): MessageChannel is critically necessary for IE/Edge,
// since window messaging doesn't always work. It's also preferred as an API
// for other browsers: it's newer, cleaner and arguably more secure.
// Unfortunately, browsers currently do not propagate user gestures via
// MessageChannel, only via window messaging. This should be re-enabled
// once browsers fix user gesture propagation.
// See:
// Safari: https://bugs.webkit.org/show_bug.cgi?id=186593
// Chrome: https://bugs.chromium.org/p/chromium/issues/detail?id=851493
// Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=1469422
const acceptsChannel = isIeBrowser(this.win_) || isEdgeBrowser(this.win_);
this.sendCommand('connect', {'acceptsChannel': acceptsChannel});
}
/**
* The client sends this message to the host upon receiving the "connect"
* message to start the main communication channel. As a payload, the message
* will contain the provided start arguments.
* @param {?Object} args
*/
sendStartCommand(args) {
let channel = null;
if (this.acceptsChannel_ && typeof this.win_.MessageChannel == 'function') {
channel = new this.win_.MessageChannel();
}
if (channel) {
this.sendCommand('start', args, [channel.port2]);
// It's critical to switch to port messaging only after "start" has been
// sent. Otherwise, it won't be delivered.
this.switchToChannel_(channel.port1);
} else {
this.sendCommand('start', args);
}
}
/**
* Sends the specified command from the port to the host or vice versa.
* @param {string} cmd
* @param {?Object=} opt_payload
* @param {?Array=} opt_transfer
*/
sendCommand(cmd, opt_payload, opt_transfer) {
const data = {
'sentinel': SENTINEL,
'cmd': cmd,
'payload': opt_payload || null,
};
if (this.port_) {
this.port_.postMessage(data, opt_transfer || undefined);
} else {
const target = this.getTarget();
// Only "connect" command is allowed to use `targetOrigin == '*'`
const targetOrigin =
cmd == 'connect' ?
(this.targetOrigin_ != null ? this.targetOrigin_ : '*') :
this.getTargetOrigin();
target.postMessage(data, targetOrigin, opt_transfer || undefined);
}
}
/**
* Sends a message to the client.
* @param {!Object} payload
*/
customMessage(payload) {
this.sendCommand('msg', payload);
}
/**
* Registers a callback to receive messages from the client.
* @param {function(!Object)} callback
*/
onCustomMessage(callback) {
this.onCustomMessage_ = callback;
}
/**
* @param {string=} opt_name
* @return {!Promise<!MessagePort>}
*/
startChannel(opt_name) {
const name = opt_name || '';
const channelObj = this.getChannelObj_(name);
if (!channelObj.port1) {
const channel = new this.win_.MessageChannel();
channelObj.port1 = channel.port1;
channelObj.port2 = channel.port2;
channelObj.resolver(channelObj.port1);
}
if (channelObj.port2) {
// Not yet sent.
this.sendCommand('cnset', {'name': name}, [channelObj.port2]);
channelObj.port2 = null;
}
return channelObj.promise;
}
/**
* @param {string=} opt_name
* @return {!Promise<!MessagePort>}
*/
askChannel(opt_name) {
const name = opt_name || '';
const channelObj = this.getChannelObj_(name);
if (!channelObj.port1) {
this.sendCommand('cnget', {'name': name});
}
return channelObj.promise;
}
/**
* @param {string} name
* @param {!MessagePort} port
* @private
*/
receiveChannel_(name, port) {
const channelObj = this.getChannelObj_(name);
channelObj.port1 = port;
channelObj.resolver(port);
}
/**
* @param {string} name
* @return {!ChannelHolder}
*/
getChannelObj_(name) {
if (!this.channels_) {
this.channels_ = {};
}
let channelObj = this.channels_[name];
if (!channelObj) {
let resolver;
const promise = new Promise(resolve => {
resolver = resolve;
});
channelObj = {
port1: null,
port2: null,
resolver,
promise,
};
this.channels_[name] = channelObj;
}
return channelObj;
}
/**
* @param {!MessagePort} port
* @private
*/
switchToChannel_(port) {
if (this.port_) {
closePort(this.port_);
}
this.port_ = port;
this.port_.onmessage = event => {
const data = event.data;
const cmd = data && data['cmd'];
const payload = data && data['payload'] || null;
if (cmd) {
this.handleCommand_(cmd, payload, event);
}
};
// Even though all messaging will switch to ports, the window-based message