@webext-core/messaging 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -112
- package/lib/index.cjs +28 -19
- package/lib/index.d.ts +107 -19
- package/lib/index.global.js +1155 -0
- package/lib/index.js +28 -19
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -1,136 +1,36 @@
|
|
|
1
1
|
# `@webext-core/messaging`
|
|
2
2
|
|
|
3
|
-
A light
|
|
3
|
+
A light-weight, type-safe wrapper around the `browser.runtime` messaging APIs.
|
|
4
4
|
|
|
5
|
-
In addition to adding types, it also includes error handling. Any errors will be returned to where `sendMessage` was called.
|
|
6
|
-
|
|
7
|
-
## Usage
|
|
8
|
-
|
|
9
|
-
In your project, create a file that calls `defineExtensionMessaging`, and exports the two functions it returns.
|
|
10
|
-
|
|
11
|
-
###### messaging.ts
|
|
12
|
-
|
|
13
|
-
<!-- prettier-ignore -->
|
|
14
5
|
```ts
|
|
15
|
-
|
|
6
|
+
// ./messaging.ts
|
|
7
|
+
import { ProtocolWithReturn, defineExtensionMessaging } from '@webext-core/messaging';
|
|
16
8
|
|
|
17
|
-
// This defines the data and return types used for each message
|
|
18
9
|
interface ProtocolMap {
|
|
19
|
-
|
|
20
|
-
message2: string; // Only data
|
|
21
|
-
message3: ProtocolWithReturn<undefined, boolean>; // Only a return type
|
|
22
|
-
message4: ProtocolWithReturn<string, boolean>; // Data and return type
|
|
10
|
+
getStringLength: ProtocolWithReturn<string, number>;
|
|
23
11
|
}
|
|
24
12
|
|
|
25
13
|
export const { sendMessage, onMessage } = defineExtensionMessaging<ProtocolMap>();
|
|
26
14
|
```
|
|
27
15
|
|
|
28
|
-
Then import those functions throughout the rest of the extension.
|
|
29
|
-
|
|
30
|
-
###### src/background.ts
|
|
31
|
-
|
|
32
16
|
```ts
|
|
17
|
+
// ./background.ts
|
|
33
18
|
import { onMessage } from './messaging';
|
|
34
19
|
|
|
35
|
-
onMessage('
|
|
36
|
-
|
|
37
|
-
return !!message.data;
|
|
20
|
+
onMessage('getStringLength', message => {
|
|
21
|
+
return message.data.length;
|
|
38
22
|
});
|
|
39
23
|
```
|
|
40
24
|
|
|
41
|
-
###### src/popup.ts
|
|
42
|
-
|
|
43
25
|
```ts
|
|
26
|
+
// ./content-script.js or anywhere else
|
|
44
27
|
import { sendMessage } from './messaging';
|
|
45
28
|
|
|
46
|
-
sendMessage('
|
|
47
|
-
```
|
|
48
|
-
|
|
49
|
-
## API
|
|
50
|
-
|
|
51
|
-
### `defineExtensionMessaging`
|
|
52
|
-
|
|
53
|
-
Returns [`sendMessage`](#sendmessage) and [`onMessage`](#onmessage) with types based on your [`TProtocolMap`](#protocolmap).
|
|
54
|
-
|
|
55
|
-
```ts
|
|
56
|
-
function defineExtensionMessaging<TProtocolMap>(options: ExtensionMessagingConfig): {
|
|
57
|
-
sendMessage: Function;
|
|
58
|
-
onMessage: Function;
|
|
59
|
-
};
|
|
60
|
-
```
|
|
61
|
-
|
|
62
|
-
#### `ExtensionMessagingConfig`
|
|
63
|
-
|
|
64
|
-
Configuration for the [`defineExtensionMessaging`](#defineextensionmessaging).
|
|
65
|
-
|
|
66
|
-
- `logger` (_default: `console`_): custom logger for printing sent and recieved messages to the console. Pass `null` to disable logging.
|
|
67
|
-
|
|
68
|
-
### `sendMessage`
|
|
69
|
-
|
|
70
|
-
Send a message to the background, or include a `tabId` to send a message from the background to a specific tab.
|
|
29
|
+
const length = await sendMessage('getStringLength', 'hello world');
|
|
71
30
|
|
|
72
|
-
|
|
73
|
-
function sendMessage(
|
|
74
|
-
type: keyof TProtocolMap,
|
|
75
|
-
payload: TPayload,
|
|
76
|
-
tabId?: number,
|
|
77
|
-
): Promise<TReturnType>;
|
|
78
|
-
```
|
|
79
|
-
|
|
80
|
-
### `onMessage`
|
|
81
|
-
|
|
82
|
-
Add a `runtime.onMessage` listener for a specific message type:
|
|
83
|
-
|
|
84
|
-
```ts
|
|
85
|
-
function onMessage(
|
|
86
|
-
type: keyof TProtocolMap,
|
|
87
|
-
onRecieved: (message: Message<TPayload>) => TReturnType,
|
|
88
|
-
): RemoveOnMessage;
|
|
89
|
-
```
|
|
90
|
-
|
|
91
|
-
The `onRecieved` callback's `message` includes:
|
|
92
|
-
|
|
93
|
-
- `id: number`: a unique ID for the message that was sent. Useful for debugging.
|
|
94
|
-
- `data: TPayload`: The payload sent when calling `sendMessage`, or `undefined` if no payload was sent.
|
|
95
|
-
- `sender: MessageSender`: The details about who sent the message. See [Chrome's docs on `MessageSender`](https://developer.chrome.com/docs/extensions/reference/runtime/#type-MessageSender) for more details.
|
|
96
|
-
- `timestamp: number`: MS since epoch that the message was sent at.
|
|
97
|
-
|
|
98
|
-
`onMessage` returns a function that removes the listener you just added. It accepts no arguments and returns void (`() => void`)
|
|
99
|
-
|
|
100
|
-
```ts
|
|
101
|
-
const removeListener = onMessage("some-type", ...);
|
|
102
|
-
removeListener();
|
|
103
|
-
```
|
|
104
|
-
|
|
105
|
-
### `ProtocolMap`
|
|
106
|
-
|
|
107
|
-
To implement custom types, you need to include a `ProtocolMap` when calling [`defineExtensionMessaging`](#defineextensionmessaging).
|
|
108
|
-
|
|
109
|
-
A protocol map is a record of message types to the payload and/or return type of the message.
|
|
110
|
-
|
|
111
|
-
If I wanted a message called `toRgb` to take in a hex color, and returns the R, G, and B values, it would look like this:
|
|
112
|
-
|
|
113
|
-
```ts
|
|
114
|
-
import { ProtocolWithReturn, defineExtensionMessaging } from '@webext-core/messaging';
|
|
115
|
-
|
|
116
|
-
interface ProtocolMap {
|
|
117
|
-
toRgb: ProtocolWithReturn<string, { r: number; g: number; b: number }>;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
export const { sendMessage, onMessage } = defineExtensionMessaging<ProtocolMap>();
|
|
121
|
-
```
|
|
122
|
-
|
|
123
|
-
Here's a cheatsheet for defining a protocol map:
|
|
124
|
-
|
|
125
|
-
```ts
|
|
126
|
-
interface ProtocolMap {
|
|
127
|
-
'no-payload-no-return-type': undefined;
|
|
128
|
-
'with-payload-no-return-type': YourPayloadType;
|
|
129
|
-
'no-payload-with-return-type': ProtocolWithReturn<undefined, YourReturnType>;
|
|
130
|
-
'with-payload-with-return-type': ProtocolWithReturn<YourPayloadType, YourReturnType>;
|
|
131
|
-
}
|
|
31
|
+
console.log(length); // 11
|
|
132
32
|
```
|
|
133
33
|
|
|
134
|
-
|
|
34
|
+
## Get Started
|
|
135
35
|
|
|
136
|
-
|
|
36
|
+
See [documentation](https://webext-core.aklinker1.io/messaging) to get started!
|
package/lib/index.cjs
CHANGED
|
@@ -52,22 +52,28 @@ module.exports = __toCommonJS(src_exports);
|
|
|
52
52
|
var import_webextension_polyfill = __toESM(require("webextension-polyfill"), 1);
|
|
53
53
|
function defineExtensionMessaging(config) {
|
|
54
54
|
let rootListener;
|
|
55
|
+
function cleanupRootListener() {
|
|
56
|
+
if (Object.entries(keyListeners).length === 0) {
|
|
57
|
+
import_webextension_polyfill.default.runtime.onMessage.removeListener(rootListener);
|
|
58
|
+
rootListener = void 0;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
55
61
|
let keyListeners = {};
|
|
56
62
|
let idSeq = Math.floor(Math.random() * 1e4);
|
|
57
63
|
function getNextId() {
|
|
58
64
|
return idSeq++;
|
|
59
65
|
}
|
|
60
|
-
function onMessage(
|
|
66
|
+
function onMessage(type, onReceived) {
|
|
61
67
|
var _a, _b, _c;
|
|
62
68
|
if (rootListener == null) {
|
|
63
69
|
(_a = config == null ? void 0 : config.logger) == null ? void 0 : _a.debug(
|
|
64
|
-
`[messaging] ${
|
|
70
|
+
`[messaging] ${type} initialized message listener for this context`
|
|
65
71
|
);
|
|
66
72
|
rootListener = (message, sender) => {
|
|
67
73
|
var _a2, _b2, _c2;
|
|
68
|
-
if (typeof message.
|
|
74
|
+
if (typeof message.type != "string" || typeof message.timestamp !== "number") {
|
|
69
75
|
const err = Error(
|
|
70
|
-
`[messaging] Unknown message format, must include the '
|
|
76
|
+
`[messaging] Unknown message format, must include the 'type' & 'timestamp' fields, received: ${JSON.stringify(
|
|
71
77
|
message
|
|
72
78
|
)}`
|
|
73
79
|
);
|
|
@@ -76,8 +82,8 @@ function defineExtensionMessaging(config) {
|
|
|
76
82
|
}
|
|
77
83
|
(_b2 = config == null ? void 0 : config.logger) == null ? void 0 : _b2.debug("[messaging] Received message", message, sender);
|
|
78
84
|
const entries = Object.entries(keyListeners);
|
|
79
|
-
for (const [
|
|
80
|
-
if (message.
|
|
85
|
+
for (const [type2, listener] of entries) {
|
|
86
|
+
if (message.type !== type2)
|
|
81
87
|
continue;
|
|
82
88
|
(_c2 = config == null ? void 0 : config.logger) == null ? void 0 : _c2.debug(`[messaging] onMessage {id=${message.id}} \u140A\u2500`, message);
|
|
83
89
|
const res = listener({
|
|
@@ -101,34 +107,31 @@ function defineExtensionMessaging(config) {
|
|
|
101
107
|
});
|
|
102
108
|
}
|
|
103
109
|
return Promise.resolve({
|
|
104
|
-
err: `Listener not found for message.type="${message.
|
|
110
|
+
err: `Listener not found for message.type="${message.type}".
|
|
105
111
|
|
|
106
112
|
Did you forget to call \`onMessage("getLength", ...)\`?`
|
|
107
113
|
});
|
|
108
114
|
};
|
|
109
115
|
import_webextension_polyfill.default.runtime.onMessage.addListener(rootListener);
|
|
110
116
|
}
|
|
111
|
-
if (keyListeners[
|
|
117
|
+
if (keyListeners[type] != null) {
|
|
112
118
|
const err = Error(
|
|
113
|
-
`[messaging] In this JS context, only one listener can be setup for ${
|
|
119
|
+
`[messaging] In this JS context, only one listener can be setup for ${type}`
|
|
114
120
|
);
|
|
115
121
|
(_b = config == null ? void 0 : config.logger) == null ? void 0 : _b.error(err);
|
|
116
122
|
throw err;
|
|
117
123
|
}
|
|
118
|
-
keyListeners[
|
|
119
|
-
(_c = config == null ? void 0 : config.logger) == null ? void 0 : _c.log(`[messaging] Added listener for ${
|
|
124
|
+
keyListeners[type] = onReceived;
|
|
125
|
+
(_c = config == null ? void 0 : config.logger) == null ? void 0 : _c.log(`[messaging] Added listener for ${type}`);
|
|
120
126
|
return function removeListener() {
|
|
121
|
-
delete keyListeners[
|
|
122
|
-
|
|
123
|
-
import_webextension_polyfill.default.runtime.onMessage.removeListener(rootListener);
|
|
124
|
-
rootListener = void 0;
|
|
125
|
-
}
|
|
127
|
+
delete keyListeners[type];
|
|
128
|
+
cleanupRootListener();
|
|
126
129
|
};
|
|
127
130
|
}
|
|
128
|
-
function sendMessage(
|
|
131
|
+
function sendMessage(type, data, tabId) {
|
|
129
132
|
return __async(this, null, function* () {
|
|
130
133
|
var _a, _b;
|
|
131
|
-
const message = { id: getNextId(),
|
|
134
|
+
const message = { id: getNextId(), type, data, timestamp: Date.now() };
|
|
132
135
|
(_a = config == null ? void 0 : config.logger) == null ? void 0 : _a.debug(`[messaging] sendMessage {id=${message.id}} \u2500\u1405`, message);
|
|
133
136
|
let response;
|
|
134
137
|
if (tabId == null)
|
|
@@ -142,7 +145,13 @@ Did you forget to call \`onMessage("getLength", ...)\`?`
|
|
|
142
145
|
return res;
|
|
143
146
|
});
|
|
144
147
|
}
|
|
145
|
-
|
|
148
|
+
function removeAllMessageListeners() {
|
|
149
|
+
Object.keys(keyListeners).forEach((type) => {
|
|
150
|
+
delete keyListeners[type];
|
|
151
|
+
});
|
|
152
|
+
cleanupRootListener();
|
|
153
|
+
}
|
|
154
|
+
return { onMessage, sendMessage, removeAllMessageListeners };
|
|
146
155
|
}
|
|
147
156
|
// Annotate the CommonJS export names for ESM import in node:
|
|
148
157
|
0 && (module.exports = {
|
package/lib/index.d.ts
CHANGED
|
@@ -1,30 +1,118 @@
|
|
|
1
1
|
import { Runtime } from 'webextension-polyfill';
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* Interface used to log text to the console when sending and recieving messages.
|
|
5
|
+
*/
|
|
6
|
+
interface Logger {
|
|
7
|
+
debug(...args: any[]): void;
|
|
8
|
+
log(...args: any[]): void;
|
|
9
|
+
warn(...args: any[]): void;
|
|
10
|
+
error(...args: any[]): void;
|
|
11
|
+
}
|
|
3
12
|
interface ExtensionMessagingConfig {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
13
|
+
/**
|
|
14
|
+
* The logger to use when logging messages. Defaults to `console`.
|
|
15
|
+
*
|
|
16
|
+
* Set to `null` to disable logging.
|
|
17
|
+
*/
|
|
18
|
+
logger?: Logger;
|
|
10
19
|
}
|
|
11
|
-
|
|
20
|
+
/**
|
|
21
|
+
* Used to add a return type to a message in the protocol map.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* interface ProtocolMap {
|
|
25
|
+
* // data is a string, returns undefined
|
|
26
|
+
* type1: string;
|
|
27
|
+
* // data is a string, returns a number
|
|
28
|
+
* type2: ProtocolWithReturn<string, number>;
|
|
29
|
+
* }
|
|
30
|
+
*
|
|
31
|
+
* > Internally, this is just an object with random keys for the data and return types.
|
|
32
|
+
*/
|
|
33
|
+
declare type ProtocolWithReturn<TData, TReturn> = {
|
|
12
34
|
BtVgCTPYZu: TData;
|
|
13
|
-
RrhVseLgZW:
|
|
35
|
+
RrhVseLgZW: TReturn;
|
|
14
36
|
};
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
37
|
+
/**
|
|
38
|
+
* Given a `ProtocolWithReturn` or a value, return the message's data type.
|
|
39
|
+
*/
|
|
40
|
+
declare type GetDataType<T> = T extends ProtocolWithReturn<any, any> ? T['BtVgCTPYZu'] : T;
|
|
41
|
+
/**
|
|
42
|
+
* Given a `ProtocolWithReturn` or a value, return the message's return type.
|
|
43
|
+
*/
|
|
44
|
+
declare type GetReturnType<T> = T extends ProtocolWithReturn<any, any> ? T['RrhVseLgZW'] : void;
|
|
45
|
+
/**
|
|
46
|
+
* Either a Promise of a type, or that type directly. Used to indicate that a method can by sync or
|
|
47
|
+
* async.
|
|
48
|
+
*/
|
|
49
|
+
declare type MaybePromise<T> = Promise<T> | T;
|
|
50
|
+
/**
|
|
51
|
+
* Call to ensure an active listener has been removed.
|
|
52
|
+
*
|
|
53
|
+
* If the listener has already been removed with `Messenger.removeAllListeners`, this is a noop.
|
|
54
|
+
*/
|
|
55
|
+
declare type RemoveListenerCallback = () => void;
|
|
56
|
+
declare type OnMessageReceived<TProtocolMap, TType extends keyof TProtocolMap> = (message: Message<TProtocolMap, TType>) => MaybePromise<GetReturnType<TProtocolMap[TType]>>;
|
|
57
|
+
/**
|
|
58
|
+
* Use the functions defined in the messenger to send and recieve messages throughout your entire extension.
|
|
59
|
+
*
|
|
60
|
+
* Unlike the regular `chrome.runtime` messaging APIs, there are no limitations to when you call `onMessage` or `sendMessage`.
|
|
61
|
+
*/
|
|
62
|
+
interface Messenger<TProtocolMap> {
|
|
63
|
+
/**
|
|
64
|
+
* Send a message to the background or a specific tab if `tabId` is passed. You can call this
|
|
65
|
+
* function anywhere in your extension.
|
|
66
|
+
*
|
|
67
|
+
* If you haven't setup a listener for the sent `type`, an error will be thrown.
|
|
68
|
+
*
|
|
69
|
+
* @param type The message type being sent. Call `onMessage` with the same type to listen for that message.
|
|
70
|
+
* @param data The data to send with the message.
|
|
71
|
+
* @param tabId An optional ID specifying which tab the message should be sent to.
|
|
72
|
+
*/
|
|
73
|
+
sendMessage<TType extends keyof TProtocolMap>(type: TType, data: GetDataType<TProtocolMap[TType]>, tabId?: number): Promise<GetReturnType<TProtocolMap[TType]>>;
|
|
74
|
+
/**
|
|
75
|
+
* Trigger a callback when a message of the requested type is recieved. You cannot setup multiple
|
|
76
|
+
* listeners for the same message type in the same JS context.
|
|
77
|
+
*
|
|
78
|
+
* To remove the listener, call the returned message.
|
|
79
|
+
*
|
|
80
|
+
* @param type The message type to listen for. Call `sendMessage` with the same type to triggern this listener.
|
|
81
|
+
* @param onReceived The callback executed when a message is recieved.
|
|
82
|
+
*/
|
|
83
|
+
onMessage<TType extends keyof TProtocolMap>(type: TType, onReceived: OnMessageReceived<TProtocolMap, TType>): RemoveListenerCallback;
|
|
84
|
+
/**
|
|
85
|
+
* Removes all listeners.
|
|
86
|
+
*/
|
|
87
|
+
removeAllMessageListeners(): void;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Contains information about the message recieved.
|
|
91
|
+
*/
|
|
92
|
+
interface Message<TProtocolMap, TType extends keyof TProtocolMap> {
|
|
93
|
+
/**
|
|
94
|
+
* A semi-unique, auto-incrementing number used to trace messages being sent.
|
|
95
|
+
*/
|
|
18
96
|
id: number;
|
|
19
|
-
|
|
97
|
+
/**
|
|
98
|
+
* The data that was passed into `sendMessage`
|
|
99
|
+
*/
|
|
100
|
+
data: GetDataType<TProtocolMap[TType]>;
|
|
101
|
+
/**
|
|
102
|
+
* See [`MessageSender`](https://developer.chrome.com/docs/extensions/reference/runtime/#type-MessageSender).
|
|
103
|
+
* This contains information about which JS context sent the message.
|
|
104
|
+
*/
|
|
20
105
|
sender: Runtime.MessageSender;
|
|
106
|
+
/**
|
|
107
|
+
* The timestamp the message was sent in MS since epoch.
|
|
108
|
+
*/
|
|
21
109
|
timestamp: number;
|
|
22
110
|
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
111
|
+
/**
|
|
112
|
+
* Creates a new `Messenger` used to send and recieve messages in your extension.
|
|
113
|
+
*
|
|
114
|
+
* @param config Configure the behavior of the messenger.
|
|
115
|
+
*/
|
|
116
|
+
declare function defineExtensionMessaging<TProtocolMap>(config?: ExtensionMessagingConfig): Messenger<TProtocolMap>;
|
|
29
117
|
|
|
30
|
-
export { ExtensionMessagingConfig, ProtocolWithReturn, defineExtensionMessaging };
|
|
118
|
+
export { ExtensionMessagingConfig, GetDataType, GetReturnType, Logger, MaybePromise, Messenger, ProtocolWithReturn, RemoveListenerCallback, defineExtensionMessaging };
|