This commit is contained in:
IndieKKY
2024-10-05 20:46:33 +08:00
parent 69453f7bce
commit 1bae3f8406
4 changed files with 61 additions and 51 deletions

View File

@@ -4,10 +4,12 @@ import Layer1Protocol from './Layer1Protocol'
export type PortContext = { export type PortContext = {
id: string id: string
name: string name: string
tabId: number
type: 'inject' | 'app'
port: chrome.runtime.Port port: chrome.runtime.Port
portMessageHandler: Layer1Protocol portMessageHandler: Layer1Protocol
ready: boolean
tabId?: number
type?: 'inject' | 'app'
} }
class ExtensionMessage { class ExtensionMessage {
@@ -68,42 +70,43 @@ class ExtensionMessage {
const id = crypto.randomUUID() const id = crypto.randomUUID()
const name = port.name const name = port.name
const portMessageHandler = new Layer1Protocol<MessageData, MessageResult>(async (value: MessageData) => {
// 初始化
if (value.method === '_init') {
const type = value.params.type
let tabId = value.params.tabId
const listener = async (firstMessage: any) => {
console.log('firstMessage', name, firstMessage)
let tabId = firstMessage.tabId
let type = firstMessage.type
if (tabId == null) {
//get current tabId //get current tabId
if (tabId == null) {
const tabs = await chrome.tabs.query({ const tabs = await chrome.tabs.query({
active: true, active: true,
currentWindow: true, currentWindow: true,
}) })
tabId = tabs[0]?.id tabId = tabs[0]?.id
console.log('current tabId: ', tabId)
} }
if (tabId != null) {
// @ts-ignore portContext.tabId = tabId
const portContext: PortContext = {id, name, tabId, port, type} portContext.type = type
const portMessageHandler = new Layer1Protocol<MessageData, MessageResult>(async (value: MessageData) => { portContext.ready = true
return {
success: true,
code: 200,
} as MessageResult
}
return handler(value, portContext) return handler(value, portContext)
}, port) }, port)
portContext.portMessageHandler = portMessageHandler const portContext: PortContext = {id, name, port, portMessageHandler, ready: false}
this.portIdToPort.set(id, portContext) this.portIdToPort.set(id, portContext)
// 移除监听
port.onMessage.removeListener(listener)
// 开始监听 // 开始监听
portMessageHandler.startListen() portMessageHandler.startListen()
} else {
console.log('no tabId>>>', name)
}
}
port.onMessage.addListener(listener)
// 监听断开连接
port.onDisconnect.addListener(() => { port.onDisconnect.addListener(() => {
this.portIdToPort.delete(id) this.portIdToPort.delete(id)
this.debug('onDisconnect', id)
}) })
}) })
} }
@@ -113,7 +116,7 @@ class ExtensionMessage {
const targetType = target === MESSAGE_TARGET_INJECT ? 'inject' : 'app' const targetType = target === MESSAGE_TARGET_INJECT ? 'inject' : 'app'
let resp: MessageResult | undefined let resp: MessageResult | undefined
for (const portContext of this.portIdToPort.values()) { for (const portContext of this.portIdToPort.values()) {
if (tabIds.includes(portContext.tabId)) { if (tabIds.includes(portContext.tabId!)) {
if (targetType === portContext.type) { if (targetType === portContext.type) {
try { try {
const messageData: MessageData = {target, method, params, from: 'extension'} const messageData: MessageData = {target, method, params, from: 'extension'}

View File

@@ -68,13 +68,18 @@ class InjectMessage {
init(methods: { init(methods: {
[key: string]: (params: any, context: MethodContext) => Promise<any> [key: string]: (params: any, context: MethodContext) => Promise<any>
}) { }) {
this.methods = methods
this.port = chrome.runtime.connect(import.meta.env.VITE_EXTENSION_ID, { this.port = chrome.runtime.connect(import.meta.env.VITE_EXTENSION_ID, {
name: MESSAGE_TARGET_INJECT, name: MESSAGE_TARGET_INJECT,
}) })
this.portMessageHandler = new Layer1Protocol<MessageData, MessageResult>(this.messageHandler, this.port) this.portMessageHandler = new Layer1Protocol<MessageData, MessageResult>(this.messageHandler, this.port)
this.portMessageHandler!.startListen() this.portMessageHandler!.startListen()
this.portMessageHandler!.init('inject') this.portMessageHandler!.sendMessage({
this.methods = methods method: '_init',
params: {
type: 'inject',
},
} as MessageData)
} }
sendExtension = async <T = any>(method: string, params?: any): Promise<T> => { sendExtension = async <T = any>(method: string, params?: any): Promise<T> => {

View File

@@ -30,12 +30,12 @@ class Layer1Protocol<L1Req = any, L1Res = any> {
this.handler = handler this.handler = handler
} }
init(type: 'inject' | 'app', tabId?: number) { // init(type: 'inject' | 'app', tabId?: number) {
this.port.postMessage({ // this.port.postMessage({
type, // type,
tabId, // tabId,
}) // })
} // }
startListen() { startListen() {
// 持久监听 port.onMessage // 持久监听 port.onMessage

View File

@@ -77,17 +77,19 @@ const useMessageService = (methods?: {
if (messageHandler && port) { if (messageHandler && port) {
const pmh = new Layer1Protocol<MessageData, MessageResult>(messageHandler, port) const pmh = new Layer1Protocol<MessageData, MessageResult>(messageHandler, port)
pmh.startListen()
//get tabId from url params //get tabId from url params
let tabId = window.location.search.split('tabId=')[1] let tabIdStr = window.location.search.split('tabId=')[1]
if (!tabId) { let tabId = tabIdStr ? parseInt(tabIdStr) : undefined
pmh.startListen() // 初始化
pmh.init('app') pmh.sendMessage({
method: '_init',
params: {
type: 'app',
tabId,
},
} as MessageData)
portMessageHandlerInit = true portMessageHandlerInit = true
}else {
pmh.startListen()
pmh.init('app', parseInt(tabId))
portMessageHandlerInit = true
}
return pmh return pmh
} }