2021-05-08 17:52:29 +08:00
|
|
|
import {PluginEvent, Page, Msg} from "@/core/types";
|
2021-04-26 22:27:47 +08:00
|
|
|
|
|
|
|
class ConnectBackground {
|
|
|
|
connect: chrome.runtime.Port | null = null;
|
|
|
|
|
|
|
|
constructor() {
|
2021-11-04 21:01:33 +08:00
|
|
|
this._initConnect();
|
|
|
|
}
|
|
|
|
|
|
|
|
private _initConnect() {
|
2021-04-26 22:27:47 +08:00
|
|
|
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(() => {
|
2021-11-04 21:01:33 +08:00
|
|
|
console.log(`%c[Connect-Dis]`, "color:red;")
|
2021-04-26 22:27:47 +08:00
|
|
|
this.connect = null;
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
onBackgroundMessage(cb: Function) {
|
|
|
|
if (this.connect) {
|
|
|
|
this.connect.onMessage.addListener((event, sender) => {
|
|
|
|
cb && cb(event, sender)
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-04 21:01:33 +08:00
|
|
|
postMessageToBackground(msg: Msg, data?: any) {
|
2021-04-26 22:27:47 +08:00
|
|
|
if (this.connect) {
|
2021-05-08 17:52:29 +08:00
|
|
|
let sendData = new PluginEvent(Page.Devtools, Page.Background, msg, data)
|
|
|
|
this.connect.postMessage(sendData)
|
2021-04-26 22:27:47 +08:00
|
|
|
} else {
|
2021-11-04 21:01:33 +08:00
|
|
|
console.warn("重新和background建立链接")
|
|
|
|
this._initConnect();
|
|
|
|
this.postMessageToBackground(msg, data)
|
2021-04-26 22:27:47 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
export const connectBackground = new ConnectBackground();
|