-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathsysend.js
912 lines (890 loc) · 33.8 KB
/
sysend.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
/**@license
* sysend.js - send messages between browser windows/tabs version 1.17.5
*
* Copyright (C) 2014 Jakub T. Jankiewicz <https://jcubic.pl/me>
* Released under the MIT license
*
* The idea for localStorage implementation came from this StackOverflow question:
* http://stackoverflow.com/q/24182409/387194
*
*/
/* global define, module, exports, Symbol, Promise */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['sysend'], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.sysend = factory();
}
})(typeof window !== 'undefined' ? window : this, function() {
var DEBUG = false;
var collecting_timeout = 400;
// we use prefix so `foo' event don't collide with `foo' locaStorage value
var uniq_prefix = '___sysend___';
var prefix_re = new RegExp(uniq_prefix, 'g');
var random_value = Math.random();
var serializer = {};
// object with user events as keys and values arrays of callback functions
var callbacks = {};
var has_primary;
var iframes = [];
var index = 0;
var proxy_mode = false;
var channel;
var primary = true;
var force_ls = false;
// we use id because storage event is not executed if message was not
// changed, and we want it if user send same object twice (before it will
// be removed)
var id = 0;
// identifier for making each call to list unique
var list_id = 0;
// Storage Access API handler
var sa_handle;
// id of the window/tabAnd two-way communication is tracked in
var target_id = generate_uuid();
var target_count = 1;
var rpc_count = 0;
var domains;
var handlers = {
primary: [],
close: [],
open: [],
secondary: [],
message: [],
visbility: [],
ready: [],
update: []
};
var events = Object.keys(handlers);
// -------------------------------------------------------------------------
var serialize = make_process(serializer, 'to');
var unserialize = make_process(serializer, 'from');
// -------------------------------------------------------------------------
var sysend = {
id: target_id,
broadcast: function(event, data) {
if (channel && !force_ls) {
log('broadcast', { event: event, data: data });
channel.postMessage({name: event, data: serialize(data)});
} else {
set(event, to_json(data));
// clean up localstorage
setTimeout(function() {
remove(event);
}, 0);
}
send_to_iframes(event, data);
return sysend;
},
emit: function(event, data) {
log('emit', { event: event, data: data });
sysend.broadcast(event, data);
invoke(event, data);
return sysend;
},
serializer: function(to, from) {
if (!(is_function(to) && is_function(from))) {
throw new Error('sysend::serializer: Invalid argument, expecting' +
' function');
}
serializer.to = to;
serializer.from = from;
return sysend;
},
proxy: function() {
var args = Array.prototype.slice.call(arguments);
args.forEach(function(url) {
if (is_string(url) && host(url) !== window.location.host) {
domains = domains || [];
var orig = origin(url);
if (domains.includes(orig)) {
var selector = 'iframe[src="' + url + '"]';
if (document.querySelector(selector)) {
warn('You already called proxy on ' + url +
' you only need to call this function once');
return;
}
}
domains.push(orig);
var iframe = document.createElement('iframe');
iframe.style.width = iframe.style.height = 0;
iframe.style.position = 'absolute';
iframe.style.top = iframe.style.left = '-9999px';
iframe.style.border = 'none';
var proxy_url = url;
if (!url.match(/\.html|\.php|\?/)) {
proxy_url = url.replace(/\/$/, '') + '/proxy.html';
}
iframe.addEventListener('error', function handler() {
setTimeout(function() {
throw new Error('html proxy file not found on "' + url +
'" url');
}, 0);
iframe.removeEventListener('error', handler);
});
iframe.addEventListener('load', function handler() {
var win;
// fix for Safari
// https://stackoverflow.com/q/42632188/387194
try {
win = iframe.contentWindow;
} catch(e) {
win = iframe.contentWindow;
}
iframes.push({window: win, node: iframe});
iframe.removeEventListener('load', handler);
});
document.body.appendChild(iframe);
iframe.src = proxy_url;
}
});
if (!arguments.length && is_iframe) {
proxy_mode = true;
}
return sysend;
},
on: function(event, fn) {
if (!callbacks[event]) {
callbacks[event] = [];
}
callbacks[event].push(fn);
return sysend;
},
off: function(event, fn, internal) {
if (callbacks[event]) {
if (fn) {
for (var i = callbacks[event].length; i--;) {
if (callbacks[event][i] == fn) {
callbacks[event].splice(i, 1);
}
}
} else if (internal && is_internal(event) || !internal) {
callbacks[event] = [];
}
}
return sysend;
},
track: function(event, fn, internal) {
if (internal) {
fn[Symbol.for(uniq_prefix)] = true;
}
if (events.includes(event)) {
handlers[event].push(fn);
}
return sysend;
},
untrack: function(event, fn, internal) {
if (events.includes(event) && handlers[event].length) {
if (fn === undefined) {
if (internal) {
handlers[event] = [];
} else {
handlers[event] = handlers[event].filter(function(fn) {
return !fn[Symbol.for(uniq_prefix)];
});
}
} else {
handlers[event] = handlers[event].filter(function(handler) {
return handler !== fn;
});
}
}
return sysend;
},
post: function(target, data) {
return sysend.broadcast(make_internal('__message__'), {
target: target,
data: data,
origin: target_id
});
},
list: function() {
var id = list_id++;
var marker = { target: target_id, id: id, origin: self.origin };
var timer = delay(sysend.timeout);
return new Promise(function(resolve) {
var ids = [];
function handler(data) {
log('__window_ack__', { data: data, marker: marker });
if (data.origin.target === target_id && data.origin.id === id) {
ids.push({
id: data.id,
primary: data.primary
});
}
}
sysend.on(make_internal('__window_ack__'), handler);
sysend.broadcast(make_internal('__window__'), { id: marker });
timer().then(function() {
log('timeout', { ids: ids });
sysend.off(make_internal('__window_ack__'), handler);
resolve(ids);
});
});
},
channel: function() {
var args = Array.prototype.slice.call(arguments);
domains = args.map(origin);
return sysend;
},
isPrimary: function() {
return primary;
},
useLocalStorage: function(toggle) {
if (typeof toggle === 'boolean') {
force_ls = toggle;
} else {
force_ls = true;
}
},
rpc: function(object) {
var prefix = ++rpc_count;
var req = "__" + prefix + "_rpc_request__";
var res = "__" + prefix + "_rpc_response__";
var request_index = 0;
var timeout = 1000;
function request(id, method, args) {
args = args || [];
var req_id = ++request_index;
return new Promise(function(resolve, reject) {
sysend.track('message', function handler(message) {
var data = message.data;
var origin = message.origin;
if (data.type === res) {
if (origin === id && req_id === data.id) {
if (data.error) {
reject(data.error);
} else {
resolve(data.result);
}
clearTimeout(timer);
sysend.untrack('message', handler);
}
}
}, true);
var payload = {
method: method,
id: req_id,
type: req,
args: args
};
sysend.post(id, payload);
var timer = setTimeout(function() {
reject(new Error('Timeout error'));
}, timeout);
});
}
sysend.track('message', function handler(message) {
var data = message.data;
var origin = message.origin;
if (data.type == req) {
var type = res;
if (Object.hasOwn(object, data.method)) {
try {
var fn = object[data.method];
unpromise(fn.apply(object, data.args), function(result) {
sysend.post(origin, { result: result, id: data.id, type: type });
}, function(error) {
sysend.post(origin, { error: error.message, id: data.id, type: type });
});
} catch(e) {
sysend.post(origin, {
error: e.message,
id: id,
type: type
});
}
} else {
sysend.post(origin, {
error: 'Method not found',
id: id,
type: type
});
}
}
}, true);
var error_msg = 'You need to specify the target window/tab';
return Object.fromEntries(Object.keys(object).map(function(name) {
return [name, function(id) {
if (!id) {
return Promise.reject(new Error(error_msg));
}
var args = Array.prototype.slice.call(arguments, 1);
return request(id, name, args);
}];
}));
}
};
// -------------------------------------------------------------------------
Object.defineProperty(sysend, 'timeout', {
enumerable: true,
get: function() {
return collecting_timeout;
},
set: function(value) {
if (typeof value === 'number' && !isNaN(value)) {
collecting_timeout = value;
}
}
});
// -------------------------------------------------------------------------
var host = (function() {
if (typeof URL !== 'undefined') {
return function(url) {
if (!url) {
return url;
}
url = new URL(url);
return url.host;
};
}
var a = document.createElement('a');
return function(url) {
if (!url) {
return url;
}
a.href = url;
return a.host;
};
})();
// -------------------------------------------------------------------------
function unpromise(obj, callback, error) {
if (is_promise(obj)) {
var ret = obj.then(callback);
if (!error) {
return ret;
} else {
return ret.catch(error);
}
} else {
return callback(obj);
}
}
// -------------------------------------------------------------------------
function delay(time) {
return function() {
return new Promise(function(resolve) {
setTimeout(resolve, time);
});
};
}
// -------------------------------------------------------------------------
var origin = (function() {
function tc(f) {
return function origin(url) {
try {
return f(url);
} catch(e) {
return url;
}
};
}
if (window.URL) {
return tc(function origin(url) {
return new URL(url).origin;
});
}
var a = document.createElement('a');
return tc(function origin(url) {
a.href = url;
return a.origin;
});
})();
// -------------------------------------------------------------------------
// :: show only single message of this kind
// -------------------------------------------------------------------------
var warn_messages = [];
function warn(message) {
if (!warn_messages.includes(message)) {
warn_messages.push(message);
if (console && console.warn) {
console.warn(message);
} else {
setTimeout(function() {
throw new Error(message);
}, 0);
}
}
}
// -------------------------------------------------------------------------
function log() {
if (DEBUG) {
console.log.apply(null, [self.origin].concat(Array.from(arguments)));
}
}
// -------------------------------------------------------------------------
function iframe_loaded() {
var iframes = Array.from(document.querySelectorAll('iframe'));
return Promise.all(iframes.filter(function(iframe) {
return iframe.src;
}).map(function(iframe) {
return new Promise(function(resolve, reject) {
iframe.addEventListener('load', resolve, true);
iframe.addEventListener('error', reject, true);
});
})).then(delay(sysend.timeout));
// delay is required, something with browser, it's not intialized
// properly. The number was picked by experimentation
}
// -------------------------------------------------------------------------
function make_internal(name) {
return uniq_prefix + name;
}
// -------------------------------------------------------------------------
function is_promise(obj) {
return obj && typeof obj == 'object' && is_function(obj.then);
}
// -------------------------------------------------------------------------
function is_function(o) {
return typeof o === 'function';
}
// -------------------------------------------------------------------------
function is_string(o) {
return typeof o === 'string';
}
// -------------------------------------------------------------------------
function is_internal(name) {
return name.match(prefix_re);
}
// -------------------------------------------------------------------------
// :: valid sysend message
// -------------------------------------------------------------------------
function is_sysend_post_message(e) {
return is_string(e.data) && is_internal(e.data);
}
// -------------------------------------------------------------------------
function is_secured_iframe() {
return is_proxy_iframe() && window.isSecureContext;
}
// -------------------------------------------------------------------------
function is_valid_origin(origin) {
if (!domains) {
warn('Call sysend.channel() on iframe to restrict domains that can '+
'use sysend channel');
return true;
}
var valid = domains.includes(origin);
if (!valid) {
warn(origin + ' domain is not on the list of allowed '+
'domains use sysend.channel() on iframe to allow'+
' access to this domain');
}
return valid;
}
// -------------------------------------------------------------------------
// :: ref: https://stackoverflow.com/a/8809472/387194
// :: license: Public Domain/MIT
// -------------------------------------------------------------------------
function generate_uuid() {
var d = new Date().getTime();
//Time in microseconds since page-load or 0 if unsupported
var d2 = (performance && performance.now && (performance.now() * 1000)) || 0;
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16;
if (d > 0) { // Use timestamp until depleted
r = (d + r)%16 | 0;
d = Math.floor(d/16);
} else { // Use microseconds since page-load if supported
r = (d2 + r)%16 | 0;
d2 = Math.floor(d2/16);
}
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
}
// -------------------------------------------------------------------------
function trigger(arr) {
var args = Array.prototype.slice.call(arguments, 1);
arr.forEach(function(fn) {
fn.apply(null, args);
});
}
// -------------------------------------------------------------------------
function ls() {
if (sa_handle) {
return sa_handle.localStorage;
} else {
return localStorage;
}
}
// -------------------------------------------------------------------------
function get(key) {
log({get: key});
return ls().getItem(make_internal(key));
}
// -------------------------------------------------------------------------
function set(key, value) {
// storage event is not fired when value is set first time
log({set: key, value: value});
if (id == 0) {
ls().setItem(make_internal(key), random_value);
}
ls().setItem(make_internal(key), value);
}
// -------------------------------------------------------------------------
function remove(key) {
log({remove: key});
ls().removeItem(make_internal(key));
}
// -------------------------------------------------------------------------
function make_process(object, prop) {
var labels = {
from: 'Unserialize',
to: 'Serialize'
};
var prefix_message = labels[prop] + ' Error: ';
return function(data) {
var fn = object[prop];
try {
if (fn) {
return fn(data);
}
return data;
} catch (e) {
warn(prefix_message + e.message);
}
};
}
// -------------------------------------------------------------------------
// ref: https://stackoverflow.com/a/326076/387194
// -------------------------------------------------------------------------
var is_iframe = (function is_iframe() {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
})();
// -------------------------------------------------------------------------
var is_private_mode = (function is_private_mode() {
try {
ls().setItem(uniq_prefix, 1);
ls().removeItem(uniq_prefix);
return false;
} catch (e) {
return true;
}
})();
// -------------------------------------------------------------------------
function is_proxy_iframe() {
return is_iframe && proxy_mode;
}
// -------------------------------------------------------------------------
function send_to_iframes(key, data) {
// propagate events to iframes
iframes.forEach(function(iframe) {
var payload = {
name: uniq_prefix,
key: key,
data: data
};
if (is_valid_origin(origin(iframe.node.src))) {
iframe.window.postMessage(JSON.stringify(payload), '*');
}
});
}
// -------------------------------------------------------------------------
function to_json(input) {
// save random_value in storage to fix issue in IE that storage event
// is fired on same page where setItem was called
var obj = [id++, random_value];
// undefined in array get stringified as null
if (typeof input != 'undefined') {
obj.push(input);
}
var data = serialize(obj);
if (data === obj) {
return JSON.stringify(obj);
}
return data;
}
// -------------------------------------------------------------------------
function from_json(json) {
var result = unserialize(json);
if (result === json) {
return JSON.parse(json);
}
return result;
}
// -------------------------------------------------------------------------
function invoke(key, data) {
callbacks[key].forEach(function(fn) {
fn(data, key);
});
}
// -------------------------------------------------------------------------
function init_visiblity() {
// ref: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
var hidden, visibilityChange;
if (typeof document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support
hidden = 'hidden';
visibilityChange = 'visibilitychange';
} else if (typeof document.msHidden !== 'undefined') {
hidden = 'msHidden';
visibilityChange = 'msvisibilitychange';
} else if (typeof document.webkitHidden !== 'undefined') {
hidden = 'webkitHidden';
visibilityChange = 'webkitvisibilitychange';
}
if (is_function(document.addEventListener) && hidden) {
document.addEventListener(visibilityChange, function() {
trigger(handlers.visbility, !document[hidden]);
}, false);
}
}
// -------------------------------------------------------------------------
function become_primary() {
primary = true;
trigger(handlers.primary);
sysend.emit(make_internal('__primary__'));
}
// -------------------------------------------------------------------------
function document_ready() {
return ['interactive', 'complete'].indexOf(document.readyState) !== -1;
}
// -------------------------------------------------------------------------
if (document_ready()) {
init();
} else {
window.addEventListener('load', function() {
setTimeout(init, 0);
});
}
// -------------------------------------------------------------------------
function setup_ls() {
log('setup_ls()');
// we need to clean up localStorage if broadcast called on unload
// because setTimeout will never fire, even setTimeout 0
var re = new RegExp('^' + uniq_prefix);
var localStorage = ls();
for(var key in localStorage) {
if (key.match(re)) {
localStorage.removeItem(key);
}
}
window.addEventListener('storage', function(e) {
// prevent event to be executed on remove in IE
if (e.key && e.key.match(re) && index++ % 2 === 0) {
var key = e.key.replace(re, '');
log('__key__', e.key + ' ==> ' + key, {
callbacks: callbacks[key],
again: callbacks[key.replace(re, '')]
});
if (callbacks[key]) {
var value = e.newValue || get(e.key);
if (value && value != random_value) {
var obj = from_json(value);
// don't call on remove
if (obj && obj[1] != random_value) {
invoke(key, obj[2]);
}
}
}
}
}, false);
}
// -------------------------------------------------------------------------
function setup_update_tracking(init_list) {
var list = init_list || [];
update();
function update() {
trigger(handlers.update, list);
}
sysend.track('open', function(data) {
if (data.id !== sysend.id) {
list.push(data);
log({ list: list, action: 'open' });
update();
}
}, true);
sysend.track('close', function(data) {
list = list.filter(function(tab) {
return data.id !== tab.id;
});
log({ list: list, action: 'close' });
update();
}, true);
}
// -------------------------------------------------------------------------
function setup_channel() {
if (sa_handle) {
var hasOwnProperty = Object.prototype.hasOwnProperty;
if (hasOwnProperty.call(sa_handle, 'BroadcastChannel')) {
channel = new sa_handle.BroadcastChannel(uniq_prefix);
}
} else {
channel = new window.BroadcastChannel(uniq_prefix);
}
if (!channel) {
return;
}
channel.addEventListener('message', function(event) {
if (event.target.name === uniq_prefix) {
log('message', { data: event.data, iframe: is_proxy_iframe() });
if (is_proxy_iframe()) {
var payload = {
name: uniq_prefix,
data: event.data,
iframe_id: target_id
};
if (is_valid_origin(origin(document.referrer))) {
window.parent.postMessage(JSON.stringify(payload), '*');
}
} else {
var key = event.data && event.data.name;
if (callbacks[key]) {
invoke(key, unserialize(event.data.data));
}
}
}
});
}
// -------------------------------------------------------------------------
function seutp() {
setup_channel();
if (!is_private_mode) {
setup_ls();
}
if (is_proxy_iframe()) {
window.addEventListener('message', function(e) {
if (is_sysend_post_message(e) && is_valid_origin(e.origin)) {
try {
var payload = JSON.parse(e.data);
log('iframe', payload, payload.name === uniq_prefix);
if (payload && payload.name === uniq_prefix) {
var data = unserialize(payload.data);
sysend.broadcast(payload.key, data);
}
} catch(e) {
// ignore wrong JSON, the message don't came from Sysend
// even that the string have unix_prefix, this is just in case
}
}
});
} else {
init_visiblity();
sysend.track('visbility', function(visible) {
if (visible && !has_primary) {
become_primary();
}
}, true);
sysend.on(make_internal('__primary__'), function() {
log('__primary__');
has_primary = true;
});
sysend.on(make_internal('__open__'), function(data) {
log('__open__', data);
var id = data.id;
target_count++;
if (primary) {
sysend.broadcast(make_internal('__ack__'));
}
trigger(handlers.open, {
count: target_count,
primary: data.primary,
id: data.id
});
if (id === target_id) {
trigger(handlers.ready);
}
});
sysend.on(make_internal('__ack__'), function() {
if (!primary) {
trigger(handlers.secondary);
}
});
sysend.on(make_internal('__close__'), function(data) {
log('__close__', data);
--target_count;
var last = target_count === 1;
if (data.wasPrimary && !primary) {
has_primary = false;
}
var payload = {
id: data.id,
count: target_count,
primary: data.wasPrimary,
self: data.id === target_id
};
// we need to trigger primary when tab is in different window
// and is not be hidden
if (last) {
become_primary();
}
trigger(handlers.close, payload);
});
sysend.on(make_internal('__window__'), function(data) {
log('__window__', { data: data })
sysend.broadcast(make_internal('__window_ack__'), {
id: target_id,
origin: data.id,
from: self.origin,
primary: primary
});
});
sysend.on(make_internal('__message__'), function(data) {
log('__message__', data);
if (data.target === 'primary' && primary) {
trigger(handlers.message, data);
} else if (data.target === target_id) {
trigger(handlers.message, data);
}
});
addEventListener('beforeunload', function() {
log('beforeunload');
sysend.emit(make_internal('__close__'), {
id: target_id,
wasPrimary: primary
});
}, { capture: true });
iframe_loaded().then(function() {
setTimeout(function() {
sysend.list().then(function(list) {
log('sysend.list()', list);
target_count = list.length;
primary = list.length === 0;
var found = list.find(function(item) {
return item.primary;
});
if (found || primary) {
has_primary = true;
}
sysend.emit(make_internal('__open__'), {
id: target_id,
primary: primary
});
if (primary) {
trigger(handlers.primary);
}
setup_update_tracking(list);
});
}, 0);
});
}
}
// -------------------------------------------------------------------------
function init() {
if (is_function(window.BroadcastChannel)) {
var ssa = document.requestStorageAccess && 'hasUnpartitionedCookieAccess' in document;
if (is_secured_iframe() && ssa) {
document.requestStorageAccess({
all: true
}).then(function(handle) {
sa_handle = handle;
log({init: handle});
seutp();
}).catch(seutp);
} else {
seutp();
}
return sysend;
} else if (is_private_mode) {
warn('Your browser don\'t support localStorgage. ' +
'In Safari this is most of the time because ' +
'of "Private Browsing Mode"');
}
seutp();
}
return sysend;
});