69 lines
2.4 KiB
TypeScript
Raw Normal View History

2024-12-24 17:31:26 +08:00
import { ChromeConst } from "cc-plugin/src/chrome/const";
import { Msg, Page, PluginEvent } from "../../core/types";
import { Terminal } from "../terminal";
2024-12-27 14:23:27 +08:00
import { PortMan } from "./portMan";
import { portMgr } from "./portMgr";
2024-12-24 17:31:26 +08:00
const terminal = new Terminal(Page.Background);
console.log(...terminal.init());
function isDevtools(port: chrome.runtime.Port) {
const devtoolsUrl = `chrome-extension://${port.sender?.id}/${ChromeConst.html.devtools}`;
if (port.sender?.url === devtoolsUrl) {
}
}
function onTabConnect(tab: chrome.tabs.Tab, port: chrome.runtime.Port) {
if (tab.id === undefined || tab.id <= 0) {
debugger;
return;
}
2024-12-27 14:23:27 +08:00
let portMan = portMgr.findPort(tab.id);
2024-12-24 17:31:26 +08:00
if (portMan) {
// 一个port发起多次发起链接以最后一次的为数据通讯基准
// portMgr.removePort(portMan);
}
portMan = portMgr.addPort(tab, port);
portMan.init();
}
chrome.runtime.onConnect.addListener((port: chrome.runtime.Port) => {
if (port.name === Page.Devtools) {
// devtool链接过来没有port.sender.tab
chrome.tabs.query({ active: true }, (tabs: chrome.tabs.Tab[]) => {
tabs.forEach((tab) => {
onTabConnect(tab, port);
2024-12-27 14:23:27 +08:00
});
2024-12-24 17:31:26 +08:00
});
} else {
const tab: chrome.tabs.Tab | undefined = port.sender?.tab;
if (tab) {
onTabConnect(tab, port);
}
}
});
chrome.runtime.onMessage.addListener((request: PluginEvent, sender: any, sendResponse: any) => {
2024-12-27 14:14:38 +08:00
const event = PluginEvent.create(request);
2024-12-24 17:31:26 +08:00
const tabID = sender.tab.id;
const portMan: PortMan | undefined = portMgr.findPort(tabID);
if (portMan) {
2024-12-27 14:14:38 +08:00
if (event.check(Page.Content, Page.Background)) {
2024-12-24 17:31:26 +08:00
// 监听来自content.js发来的事件将消息转发到devtools
2024-12-27 14:14:38 +08:00
event.reset(Page.Background, Page.Devtools);
2024-12-24 17:31:26 +08:00
console.log(`%c[Message]url:${sender.url}]\n${JSON.stringify(request)}`, "color:green");
portMgr.sendDevtoolMsg(request);
}
}
});
2024-12-27 14:23:27 +08:00
chrome.tabs.onActivated.addListener(({ tabId, windowId }) => {});
2024-12-24 17:31:26 +08:00
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
// 页面发生刷新,通知重新生成数据
if (changeInfo.status === "complete") {
const { id } = tab;
// -1为自己
if (id && id > -1) {
let portMan = portMgr.findPort(id);
if (portMan) {
let data = new PluginEvent(Page.Background, Page.Content, Msg.Support);
portMgr.sendContentMsg(data);
}
}
}
});