This repository was archived by the owner on May 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 216
/
Copy pathchannel.ts
89 lines (71 loc) · 2.06 KB
/
channel.ts
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
import {
Message,
MessageType,
} from '../communication';
const connections = new Map<number, chrome.runtime.Port>();
/// A queue of messages that were not able to be delivered and will be
/// retried when the connection to the content script or extension is
/// re-established
const messageBuffer = new Map<number, Array<any>>();
const drainQueue = (port: chrome.runtime.Port, buffer: Array<any>) => {
if (buffer == null || buffer.length === 0) {
return;
}
let removed = 0;
const send = (m: Message<any>, index: number) => {
port.postMessage(m);
++removed;
};
try {
buffer.forEach(send);
} catch (error) {
// port disconnected, re-try on connect.
}
buffer.splice(0, removed);
};
chrome.runtime.onMessage.addListener(
(message, sender, sendResponse) => {
if (message.messageType === MessageType.Initialize) {
sendResponse({ // note that this is separate from our message response system
extensionId: chrome.runtime.id
});
}
if (sender.tab) {
let sent = false;
const connection = connections.get(sender.tab.id);
if (connection) {
try {
connection.postMessage(message);
sent = true;
}
catch (err) {}
}
if (sent === false) {
let queue = messageBuffer.get(sender.tab.id);
if (queue == null) {
queue = new Array<any>();
messageBuffer.set(sender.tab.id, queue);
}
queue.push(message);
}
}
return true;
});
chrome.runtime.onConnect.addListener(port => {
const listener = (message, sender) => {
if (connections.has(message.tabId) === false) {
connections.set(message.tabId, port);
}
drainQueue(message.tabId, messageBuffer.get(message.tabId));
chrome.tabs.sendMessage(message.tabId, message);
};
port.onMessage.addListener(listener);
port.onDisconnect.addListener(() => {
port.onMessage.removeListener(<any> listener);
connections.forEach((value, key, map) => {
if (value === port) {
map.delete(key);
}
});
});
});