You've already forked bilibili-subtitle
消息传递重构&支持侧边面板
This commit is contained in:
@@ -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
|
||||
|
Reference in New Issue
Block a user