MCPcopy Index your code
hub / github.com/scriptscat/scriptcat / ExtensionMessage

Class ExtensionMessage

packages/message/extension_message.ts:7–156  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

5const listenerMgr = new EventEmitter<string, any>(); // 单一管理器
6
7export class ExtensionMessage implements Message {
8 constructor(private backgroundPrimary = false) {}
9
10 connect(data: TMessage): Promise<MessageConnect> {
11 return new Promise((resolve) => {
12 const con = chrome.runtime.connect();
13 con.postMessage(data);
14 resolve(new ExtensionMessageConnect(con));
15 });
16 }
17
18 // 发送消息 注意不进行回调的内存泄漏
19 sendMessage<T = any>(data: TMessage): Promise<T> {
20 return new Promise((resolve: ((value: T) => void) | null) => {
21 chrome.runtime.sendMessage(data, (resp: T) => {
22 const lastError = chrome.runtime.lastError;
23 if (lastError) {
24 console.error("chrome.runtime.lastError in chrome.runtime.sendMessage:", lastError);
25 // 通信API出错不回继续对话
26 }
27 resolve!(resp);
28 resolve = null;
29 });
30 });
31 }
32
33 tryEnableUserScriptConnectionListener = (..._args: any) => {
34 // empty function
35 };
36 tryEnableUserScriptMessageListener = (..._args: any) => {
37 // empty function
38 };
39
40 onConnect(callback: (data: TMessage, con: MessageConnect) => void) {
41 chrome.runtime.onConnect.addListener((port: chrome.runtime.Port) => {
42 let myPort: chrome.runtime.Port | null = port;
43 const lastError = chrome.runtime.lastError;
44 if (lastError) {
45 console.error("chrome.runtime.lastError in chrome.runtime.onConnect", lastError);
46 // 消息API发生错误因此不继续执行
47 }
48 const handler = (msg: TMessage) => {
49 const port = myPort;
50 if (port !== null) {
51 myPort = null;
52 port.onMessage.removeListener(handler);
53 callback(msg, new ExtensionMessageConnect(port));
54 }
55 };
56 myPort.onMessage.addListener(handler);
57 });
58
59 if (this.backgroundPrimary) {
60 let addUserScriptConnectionListener: (() => void) | null = () => {
61 try {
62 // 监听用户脚本的连接
63 chrome.runtime.onUserScriptConnect.addListener((port: chrome.runtime.Port) => {
64 let myPort: chrome.runtime.Port | null = port;

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected