webext-messenger
Advanced tools
Comparing version 0.1.0 to 0.2.0
/// <reference types="firefox-webext-browser" /> | ||
import { MessengerMethods } from "./test/demo-extension/background/types"; | ||
declare type Arguments = any[]; | ||
declare type Method = (this: browser.runtime.MessageSender, ...args: Arguments) => Promise<unknown>; | ||
export declare type Method = (this: browser.runtime.MessageSender, ...args: Arguments) => Promise<unknown>; | ||
declare type PublicMethod<TMethod = Method> = OmitThisParameter<TMethod>; | ||
/** | ||
* Returns a function that registers a handler for a specific method. | ||
* To be called in the receiving end. | ||
*/ | ||
export declare function getRegistration(type: string, method: Method): () => void; | ||
/** | ||
* Replicates the original method, including its types. | ||
* To be called in the sender’s end. | ||
*/ | ||
export declare function getMethod<TMethod extends Method>(type: string): OmitThisParameter<TMethod>; | ||
export declare function getMethod<TMethod extends Method>(type: string): PublicMethod<TMethod>; | ||
export declare function registerMethods(methods: Partial<MessengerMethods>): void; | ||
export {}; |
@@ -24,15 +24,2 @@ function isObject(value) { | ||
/** | ||
* Returns a function that registers a handler for a specific method. | ||
* To be called in the receiving end. | ||
*/ | ||
export function getRegistration(type, method) { | ||
return () => { | ||
if (handlers.has(type)) { | ||
throw new Error(`Handler already set for ${type}`); | ||
} | ||
handlers.set(type, method); | ||
browser.runtime.onMessage.addListener(onMessageListener); | ||
}; | ||
} | ||
/** | ||
* Replicates the original method, including its types. | ||
@@ -42,6 +29,16 @@ * To be called in the sender’s end. | ||
export function getMethod(type) { | ||
return (async (...args) => browser.runtime.sendMessage({ | ||
const method = async (...args) => browser.runtime.sendMessage({ | ||
type, | ||
args, | ||
})); | ||
}); | ||
return method; | ||
} | ||
export function registerMethods(methods) { | ||
for (const [type, method] of Object.entries(methods)) { | ||
if (handlers.has(type)) { | ||
throw new Error(`Handler already set for ${type}`); | ||
} | ||
handlers.set(type, method); | ||
} | ||
browser.runtime.onMessage.addListener(onMessageListener); | ||
} |
{ | ||
"name": "webext-messenger", | ||
"version": "0.1.0", | ||
"version": "0.2.0", | ||
"description": "Browser Extension component messaging framework", | ||
@@ -5,0 +5,0 @@ "keywords": [], |
6250
54