gm api通信
Some checks failed
test / Run tests (push) Failing after 9s
build / Build (push) Failing after 16s
Some checks failed
test / Run tests (push) Failing after 9s
build / Build (push) Failing after 16s
This commit is contained in:
@ -1,32 +1,24 @@
|
||||
export function sendMessage(action: string, data?: any): Promise<any> {
|
||||
return new Promise((resolve, reject) => {
|
||||
chrome.runtime.sendMessage({ action, data }, (res) => {
|
||||
if (res.code) {
|
||||
console.error(res);
|
||||
reject(res.message);
|
||||
} else {
|
||||
resolve(res.data);
|
||||
}
|
||||
});
|
||||
});
|
||||
import { Message, MessageConnect } from "./server";
|
||||
|
||||
export function sendMessage(msg: Message, action: string, data?: any): Promise<any> {
|
||||
return msg.sendMessage({ action, data });
|
||||
}
|
||||
|
||||
export function connect(action: string, data?: any): Promise<chrome.runtime.Port> {
|
||||
return new Promise((resolve) => {
|
||||
const port = chrome.runtime.connect();
|
||||
port.postMessage({ action, data });
|
||||
resolve(port);
|
||||
});
|
||||
export function connect(msg: Message, action: string, data?: any): Promise<MessageConnect> {
|
||||
return msg.connect({ action, data });
|
||||
}
|
||||
|
||||
export class Client {
|
||||
constructor(private prefix: string) {
|
||||
constructor(
|
||||
private msg: Message,
|
||||
private prefix: string
|
||||
) {
|
||||
if (!this.prefix.endsWith("/")) {
|
||||
this.prefix += "/";
|
||||
}
|
||||
}
|
||||
|
||||
do(action: string, params?: any): Promise<any> {
|
||||
return sendMessage(this.prefix + action, params);
|
||||
return sendMessage(this.msg, this.prefix + action, params);
|
||||
}
|
||||
}
|
||||
|
@ -87,3 +87,28 @@ export class Group {
|
||||
this.server.on(`${this.name}${name}`, func);
|
||||
}
|
||||
}
|
||||
|
||||
// 转发消息
|
||||
export function forwardMessage(path: string, from: Server, to: Message) {
|
||||
from.on(path, (params, fromCon) => {
|
||||
console.log(params, fromCon);
|
||||
if (fromCon) {
|
||||
to.connect({ action: path, data: params }).then((toCon) => {
|
||||
fromCon.onMessage((data) => {
|
||||
toCon.sendMessage(data);
|
||||
});
|
||||
toCon.onMessage((data) => {
|
||||
fromCon.sendMessage(data);
|
||||
});
|
||||
fromCon.onDisconnect(() => {
|
||||
toCon.disconnect();
|
||||
});
|
||||
toCon.onDisconnect(() => {
|
||||
fromCon.disconnect();
|
||||
});
|
||||
});
|
||||
} else {
|
||||
return to.sendMessage({ action: path, data: params });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
Reference in New Issue
Block a user