Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Messaging: Fix async listeners #826

Merged
merged 2 commits into from
Dec 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 Script 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