webext-messenger
Advanced tools
Comparing version
@@ -15,4 +15,4 @@ /// <reference types="firefox-webext-browser" /> | ||
*/ | ||
export declare function getMethod<TType extends keyof MessengerMethods, TMethod extends MessengerMethods[TType]>(type: TType): ActuallyOmitThisParameter<TMethod>; | ||
export declare function getMethod<TType extends keyof MessengerMethods, TMethod extends MessengerMethods[TType], PublicMethod extends ActuallyOmitThisParameter<TMethod>>(type: TType): PublicMethod; | ||
export declare function registerMethods(methods: Partial<MessengerMethods>): void; | ||
export {}; |
@@ -0,1 +1,4 @@ | ||
import isPromise from "is-promise"; | ||
import { deserializeError, serializeError } from "serialize-error"; | ||
const errorKey = "__webext_messenger_error_response__"; | ||
function isObject(value) { | ||
@@ -18,3 +21,7 @@ return typeof value === "object" && value !== null; | ||
if (handler) { | ||
return handler.call(sender, ...message.args); | ||
return handler.call(sender, ...message.args).catch((error) => ({ | ||
// Errors must be serialized because the stacktraces are currently lost on Chrome and | ||
// https://github.com/mozilla/webextension-polyfill/issues/210 | ||
[errorKey]: serializeError(error), | ||
})); | ||
} | ||
@@ -28,8 +35,20 @@ throw new Error("No handler registered for " + message.type); | ||
export function getMethod(type) { | ||
return (async (...args) => browser.runtime.sendMessage({ | ||
// Guarantees that a message is meant to be handled by this library | ||
__webext_messenger__: true, | ||
type, | ||
args, | ||
})); | ||
const publicMethod = async (...args) => { | ||
const returnValue = browser.runtime.sendMessage({ | ||
// Guarantees that a message is meant to be handled by this library | ||
__webext_messenger__: true, | ||
type, | ||
args, | ||
}); | ||
// TODO: Add test for this. The target must exist but registerMethod must have never been called | ||
if (!isPromise(returnValue)) { | ||
throw new Error("No methods were registered in the receiving end"); | ||
} | ||
const response = await returnValue; | ||
if (isObject(response) && errorKey in response) { | ||
throw deserializeError(response[errorKey]); | ||
} | ||
return response; | ||
}; | ||
return publicMethod; | ||
} | ||
@@ -36,0 +55,0 @@ export function registerMethods(methods) { |
{ | ||
"name": "webext-messenger", | ||
"version": "0.4.0", | ||
"version": "0.5.0", | ||
"description": "Browser Extension component messaging framework", | ||
@@ -71,2 +71,4 @@ "keywords": [], | ||
"dependencies": { | ||
"is-promise": "^4.0.0", | ||
"serialize-error": "^8.1.0", | ||
"webext-detect-page": "^3.0.2", | ||
@@ -73,0 +75,0 @@ "webextension-polyfill": "^0.8.0" |
7433
16.07%78
32.2%4
100%+ Added
+ Added
+ Added
+ Added
+ Added