Created
November 5, 2023 09:06
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alternative example of this file can be found at https://github.com/EduardoAC/site-review-extension/blob/master/src/contentScript/messages/sendMessage.ts