-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtablink.js
60 lines (45 loc) · 1.25 KB
/
tablink.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
const KEY_NAME = 'TABLINK';
const watchers = {};
const subscribers = new Set();
const currentTabId = (crypto || msCrypto).getRandomValues(new Uint16Array(5)).join('-');
window.addEventListener('storage', event);
function dispatch(type, message, includeOwnTab = false) {
let data = {tabId: currentTabId, type, message};
if (includeOwnTab) {
delete data.tabId;
}
data = JSON.stringify(data);
if (includeOwnTab) {
event({key: KEY_NAME, newValue: data});
}
window.localStorage.setItem(KEY_NAME, data);
localStorage.removeItem(KEY_NAME);
}
function on(type, cb) {
if (!watchers[type]) {
watchers[type] = new Set();
}
watchers[type].add(cb);
return () => watchers[type].delete(cb);
}
function subscribe(cb) {
subscribers.add(cb);
return () => subscribers.delete(cb);
}
function event(storageEvent) {
if (storageEvent.key === KEY_NAME && storageEvent.newValue !== null) {
let {tabId, type, message} = JSON.parse(storageEvent.newValue);
// The following condition exists for IE10 (not supported),
// but just in case other browsers have the same bug
if (currentTabId === tabId) {
return;
}
(watchers[type] || []).forEach(cb => cb(message));
subscribers.forEach(cb => cb(type, message));
}
}
export default {
dispatch,
on,
subscribe,
}