36 lines
881 B
TypeScript
Raw Normal View History

2021-04-28 13:59:16 +08:00
import {PluginEvent, Page} from "@/core/types";
2021-04-26 22:27:47 +08:00
class ConnectBackground {
connect: chrome.runtime.Port | null = null;
constructor() {
if (chrome && chrome.runtime) {
2021-04-28 13:59:16 +08:00
this.connect = chrome.runtime.connect({name: Page.Devtools});
2021-04-26 22:27:47 +08:00
this.connect.onDisconnect.addListener(() => {
console.log(`%c[Connect-Dis]`, 'color:red;')
this.connect = null;
})
}
}
onBackgroundMessage(cb: Function) {
if (this.connect) {
this.connect.onMessage.addListener((event, sender) => {
console.log(`[Message] ${JSON.stringify(event)}`);
cb && cb(event, sender)
});
}
}
2021-04-28 13:59:16 +08:00
postMessageToBackground(data: PluginEvent) {
2021-04-26 22:27:47 +08:00
if (this.connect) {
this.connect.postMessage(data)
} else {
console.warn('没有和background建立链接')
}
}
}
export const connectBackground = new ConnectBackground();