-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathRuntimeConnect.ts
63 lines (54 loc) · 1.54 KB
/
RuntimeConnect.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
import { GenericChannel } from './../../src/Channels/GenericChannel'
import { TransportMessage } from './../../src/Message'
export enum PortNames {
PortOne = 'PortOne',
PortTwo = 'PortTwo',
}
/**
* Channel used in an MV3 extension context
* Connection with a Service Worker background script
*/
export class RuntimeConnect extends GenericChannel {
public constructor(name: PortNames) {
super();
this.name = name;
}
private name: PortNames;
private port: chrome.runtime.Port | undefined;
/**
* Initiate a port connection
*/
public connect() {
this.setup(this.name);
}
/**
* Automatically called when a Slot is triggered and the channel is disconnected
*/
public autoReconnect() {
this.connect();
}
/**
* Send a message through the given port
*/
public send(message: any): void {
if (!this.port) {
throw new Error('No port to send message');
}
this.port.postMessage(message);
}
/**
* Setup incoming message handling, disconnections, and
* connection status when initiating a connection
*/
private setup(portName: PortNames) {
this.port = chrome.runtime.connect({ name: portName });
this.port.onMessage.addListener((message: TransportMessage) =>
this._messageReceived(message)
);
this.port.onDisconnect.addListener(() => {
this.port = undefined;
this._disconnected();
});
this._connected();
}
}