-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
68 lines (65 loc) · 1.76 KB
/
background.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
// V8
class MessageBroker {
constructor() {
this.subscribers = [];
this.currentTab = {};
chrome.tabs.onCreated.addListener((tab) => {
this.currentTab = tab;
});
chrome.tabs.onRemoved.addListener((tabId) => {
this.removeSubscriber(tabId);
this.currentTab = {};
});
}
init = (onMessage) => {
chrome.runtime.onConnect.addListener((port) => {
const { name } = port;
if (!this.currentTab.id) return;
const { id = "" } = this.currentTab;
const subscribers = this.subscribers;
subscribers.push({ id, name, port });
port.onMessage.addListener(onMessage);
port.onDisconnect.addListener(() => {
this.removeSubscriber(id);
});
});
};
removeSubscriber = (id) => {
const subscriptorIndexes = this.subscribers.reduce(
(accumulator, subscriber, index) => {
const match = subscriber.id === id;
if (match) {
accumulator.push(index);
}
return accumulator;
},
[]
);
subscriptorIndexes.forEach((subscriptorIndex) =>
this.subscribers.splice(subscriptorIndex, 1)
);
};
notify = (name, message) => {
chrome.tabs.query({ active: true }, (tabs) => {
if (tabs) {
const [tab] = tabs;
this.currentTab = tab;
const subscriptor = this.subscribers.find(
(subscriber) => subscriber.id === tab.id && subscriber.name === name
);
subscriptor?.port?.postMessage?.(message);
}
});
};
}
const broker = new MessageBroker();
broker.init((message) => {
try {
return broker.notify(message.port, message);
} catch (error) {
console.log(error);
console.log(
"Devtool has disconnected, please close and reopen the page to continue."
);
}
});