Skip to content

Commit

Permalink
Fix: Fix async listeners
Browse files Browse the repository at this point in the history
  • Loading branch information
mathieudutour committed Nov 22, 2023
1 parent 9ef619e commit 9010529
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
11 changes: 6 additions & 5 deletions api/messaging/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,19 @@ export type {
} from "./types"

/**
* Should only be called from CS or Ext Pages
* Extension Id is required to send a message from a CS in the main world
* TODO: Add a framework runtime check, using a global variable
* Send to Background Service Workers from Content Scripts or Extension pages.
* `extensionId` is required to send a message from a Content Scripts in the main world
*/
// TODO: Add a framework runtime check, using a global variable
export const sendToBackground: PlasmoMessaging.SendFx<MessageName> = async (
req
) => {
return getExtRuntime().sendMessage(req.extensionId ?? null, req)
return getExtRuntime().sendMessage(req.extensionId ?? null, req)
}

/**
* Send to CS from Ext pages or BGSW, default to active tab if no tabId is provided in the request
* Send to Content Scripts from Extension pages or Background Service Workers.
* Default to active tab if no tabId is provided in the request
*/
export const sendToContentScript: PlasmoMessaging.SendFx = async (req) => {
const tabId =
Expand Down
14 changes: 11 additions & 3 deletions api/messaging/src/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import { getExtRuntime } from "./utils"
export const listen = <RequestBody, ResponseBody>(
handler: PlasmoMessaging.Handler<string, RequestBody, ResponseBody>
) => {
const metaListener = async (req, sender, sendResponse) => {
const metaListener = async (
req: any,
sender: chrome.runtime.MessageSender,
sendResponse: (response?: ResponseBody) => void
) => {
await handler?.(
{
...req,
Expand All @@ -16,9 +20,13 @@ export const listen = <RequestBody, ResponseBody>(
)
}

const listener = (req, sender, sendResponse) => {
const listener = (
req: any,
sender: chrome.runtime.MessageSender,
sendResponse: (response?: ResponseBody) => void
) => {
metaListener(req, sender, sendResponse)
return // Syncronous return to indicate this is an async listener
return true // Synchronous return to indicate this is an async listener
}

getExtRuntime().onMessage.addListener(listener)
Expand Down

0 comments on commit 9010529

Please sign in to comment.