消息传递重构&支持侧边面板

This commit is contained in:
IndieKKY
2024-10-05 19:55:43 +08:00
parent c1c21c2fee
commit b283695b02
18 changed files with 454 additions and 214 deletions

View File

@@ -1,28 +1,19 @@
import { MESSAGE_TARGET_EXTENSION } from '@/const'
import { MESSAGE_TARGET_EXTENSION, MESSAGE_TARGET_INJECT, MESSAGE_TO_EXTENSION_ROUTE_MSG } from '@/const'
import { injectWaiter } from './useMessageService'
import { useCallback } from 'react'
import PortMessageHandler from './PortMessageHandler'
const useMessage = () => {
const sendExtension = useCallback(async <T = any>(method: string, params?: any) => {
return await chrome.runtime.sendMessage<MessageData, MessageResult>({
// wait
const portMessageHandler = await injectWaiter.wait() as PortMessageHandler<MessageData, MessageResult>
// send message
const messageResult = await portMessageHandler.sendMessage({
from: 'app',
target: MESSAGE_TARGET_EXTENSION,
method,
params: params ?? {},
}).then((messageResult) => {
if (messageResult.success) {
return messageResult.data as T
} else {
throw new Error(messageResult.message)
}
})
}, [])
const sendInject = useCallback(async <T = any>(method: string, params?: any) => {
// wait
const postInjectMessage = await injectWaiter.wait()
// send message
const messageResult = await postInjectMessage(method, params) as MessageResult | undefined
}) as MessageResult | undefined
if (messageResult != null) {
if (messageResult.success) {
return messageResult.data as T
@@ -34,6 +25,14 @@ const useMessage = () => {
}
}, [])
const sendInject = useCallback(async <T = any>(method: string, params?: any): Promise<T> => {
return await sendExtension(MESSAGE_TO_EXTENSION_ROUTE_MSG, {
target: MESSAGE_TARGET_INJECT,
method,
params: params ?? {},
})
}, [])
return {
sendExtension,
sendInject