消息通信优化

This commit is contained in:
IndieKKY
2024-10-04 14:15:08 +08:00
parent c3b53a016c
commit 8b3bd44d59
14 changed files with 308 additions and 239 deletions

View File

@@ -0,0 +1,42 @@
import { MESSAGE_TARGET_EXTENSION } from '@/const'
import { injectWaiter } from './useMessageService'
import { useCallback } from 'react'
const useMessage = () => {
const sendExtension = useCallback(async <T = any>(method: string, params?: any) => {
return await chrome.runtime.sendMessage<MessageData, MessageResult>({
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
if (messageResult != null) {
if (messageResult.success) {
return messageResult.data as T
} else {
throw new Error(messageResult.message)
}
} else {
throw new Error('no response')
}
}, [])
return {
sendExtension,
sendInject
}
}
export default useMessage