Skip to content

Instantly share code, notes, and snippets.

@salmin89
Last active September 27, 2024 15:25
Show Gist options
  • Save salmin89/d478e2888c88b38ba3ec569d83d4e179 to your computer and use it in GitHub Desktop.
Save salmin89/d478e2888c88b38ba3ec569d83d4e179 to your computer and use it in GitHub Desktop.
sendMessage utill for browser extensions
import { Channel, makeChannel } from './myutil';
const { onMessage } = makeChannel(Channel.B);
onMessage((message, sender, callback) => {
callback('background response... B');
});
export type OnMessageCb = Parameters<typeof chrome.runtime.onMessage.addListener>[number];
export enum Channel {
A = '__CHANNEL_A__',
B = '__CHANNEL_B__',
C = '__CHANNEL_C__',
}
// Utils
export function makeChannel<P = any>(channel: Channel) {
function send<R = P>(payload: P) {
return chrome.runtime.sendMessage<{ channel: Channel; payload: P }, R>({ channel, payload });
}
function middleware(callback: OnMessageCb) {
return (message: any, sender: chrome.runtime.MessageSender, sendResponse: (response: any) => void) => {
if (message.channel === channel) {
callback(message.payload, sender, sendResponse);
}
};
}
function onMessage(callback: OnMessageCb) {
chrome.runtime.onMessage.addListener(middleware(callback));
}
function unsubcribe(callback: OnMessageCb) {
chrome.runtime.onMessage.removeListener(middleware(callback));
}
return {
send,
onMessage,
unsubcribe,
};
}
import { Channel, makeChannel } from './myutil';
const { send } = makeChannel<{ foo: string; e: MouseEvent; from: string }>(Channel.B);
document.addEventListener('click', async (e) => {
// response is same as payload
const response = await send({ foo: 'bar', e, from: 'contentEnd' });
console.log(response);
// response is string
const response2 = await send<string>({ foo: 'bar', e, from: 'contentEnd' });
console.log(response);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment