Skip to content

Instantly share code, notes, and snippets.

@EduardoAC
Created November 5, 2023 09:06
Show Gist options
  • Save EduardoAC/000b1e39a6ec10a892e7c6cd93730a53 to your computer and use it in GitHub Desktop.
Save EduardoAC/000b1e39a6ec10a892e7c6cd93730a53 to your computer and use it in GitHub Desktop.
Chrome Extension - Send Message Promise Wrapper, designed for streamlined communication with the background script in Manifest v3.
export interface Message<T> {
type: string
subtype: string
data: T
}
export interface Response<V> {
status: number
data: V
}
export function sendMessage<T, V>(message: Message<T>) {
return new Promise<V>((resolve, reject) => {
try {
// You may require to adjust Response based on your project implementation
chrome.runtime.sendMessage(message, (response: Response<V>) => {
if(response.status < 400) {
resolve(response.data)
} else {
reject(response.data)
}
})
} catch (error) {
// Error must match V type
reject(error)
}
})
}
// Example using numbers
const responseDataNumber = await sendMessage<number, number>({ type: "hello", subtype: "world", data: 1})
@EduardoAC
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment