webext-messenger 0.15.0-1 → 0.15.0-5

Sign up to get free protection for your applications and to get access to all the features.
@@ -2,7 +2,7 @@ import browser from "webextension-polyfill";
2
2
  import { serializeError } from "serialize-error";
3
3
  import { messenger } from "./sender.js";
4
4
  import { handlers, isObject, MessengerError, debug, __webextMessenger, } from "./shared.js";
5
- import { getContextName } from "webext-detect-page";
5
+ import { getContextName, isBackgroundPage } from "webext-detect-page";
6
6
  import { getActionForMessage, nameThisTarget } from "./thisTarget.js";
7
7
  export function isMessengerMessage(message) {
8
8
  return (isObject(message) &&
@@ -17,7 +17,7 @@ function onMessageListener(message, sender) {
17
17
  return;
18
18
  }
19
19
  // Target check must be synchronous (`await` means we're handing the message)
20
- const action = getActionForMessage(message.target);
20
+ const action = getActionForMessage(sender, message.target);
21
21
  if (action === "ignore") {
22
22
  return;
23
23
  }
@@ -25,7 +25,9 @@ function onMessageListener(message, sender) {
25
25
  }
26
26
  // This function can only be called when the message *will* be handled locally.
27
27
  // Returning "undefined" or throwing an error will still handle it.
28
- async function handleMessage(message, sender, action) {
28
+ async function handleMessage(message, sender,
29
+ // Once messages reach handleMessage they cannot be "ignored", they're already being handled
30
+ action) {
29
31
  const { type, target, args, options: { trace } = {} } = message;
30
32
  debug(type, "↘️ received", { sender, args });
31
33
  let handleMessage;
@@ -54,7 +56,9 @@ async function handleMessage(message, sender, action) {
54
56
  });
55
57
  }
56
58
  export function registerMethods(methods) {
57
- void nameThisTarget();
59
+ if (!isBackgroundPage()) {
60
+ void nameThisTarget();
61
+ }
58
62
  for (const [type, method] of Object.entries(methods)) {
59
63
  if (handlers.has(type)) {
60
64
  throw new MessengerError(`Handler already set for ${type}`);
@@ -17,29 +17,37 @@ function makeMessage(type, args, target, options) {
17
17
  };
18
18
  }
19
19
  // Do not turn this into an `async` function; Notifications must turn `void`
20
- function manageConnection(type, options, sendMessage) {
20
+ function manageConnection(type, options, target, sendMessage) {
21
21
  if (!options.isNotification) {
22
- return manageMessage(type, sendMessage);
22
+ return manageMessage(type, target, sendMessage);
23
23
  }
24
24
  void sendMessage().catch((error) => {
25
25
  debug(type, "notification failed", { error });
26
26
  });
27
27
  }
28
- async function manageMessage(type, sendMessage) {
29
- const response = await pRetry(sendMessage, {
28
+ async function manageMessage(type, target, sendMessage) {
29
+ const response = await pRetry(async () => {
30
+ const response = await sendMessage();
31
+ if (!isMessengerResponse(response)) {
32
+ throw new MessengerError(`No handler registered for ${type} in the receiving end`);
33
+ }
34
+ return response;
35
+ }, {
30
36
  minTimeout: 100,
31
37
  factor: 1.3,
32
38
  maxRetryTime: 4000,
33
39
  onFailedAttempt(error) {
34
- if (!String(error.message).startsWith(errorNonExistingTarget)) {
40
+ if (
41
+ // Don't retry sending to the background page unless it really hasn't loaded yet
42
+ (target.page !== "background" && error instanceof MessengerError) ||
43
+ String(error.message).startsWith(errorNonExistingTarget)) {
44
+ debug(type, "will retry. Attempt", error.attemptNumber);
45
+ }
46
+ else {
35
47
  throw error;
36
48
  }
37
- debug(type, "will retry. Attempt", error.attemptNumber);
38
49
  },
39
50
  });
40
- if (!isMessengerResponse(response)) {
41
- throw new MessengerError(`No handler registered for ${type} in the receiving end`);
42
- }
43
51
  if ("error" in response) {
44
52
  debug(type, "↘️ replied with error", response.error);
45
53
  throw deserializeError(response.error);
@@ -62,11 +70,11 @@ function messenger(type, options, target, ...args) {
62
70
  debug(type, "↗️ sending message to runtime");
63
71
  return browser.runtime.sendMessage(makeMessage(type, args, target, options));
64
72
  };
65
- return manageConnection(type, options, sendMessage);
73
+ return manageConnection(type, options, target, sendMessage);
66
74
  }
67
75
  // Contexts without direct Tab access must go through background
68
76
  if (!browser.tabs) {
69
- return manageConnection(type, options, async () => {
77
+ return manageConnection(type, options, target, async () => {
70
78
  debug(type, "↗️ sending message to runtime");
71
79
  return browser.runtime.sendMessage(makeMessage(type, args, target, options));
72
80
  });
@@ -74,7 +82,7 @@ function messenger(type, options, target, ...args) {
74
82
  // `frameId` must be specified. If missing, the message is sent to every frame
75
83
  const { tabId, frameId = 0 } = target;
76
84
  // Message tab directly
77
- return manageConnection(type, options, async () => {
85
+ return manageConnection(type, options, target, async () => {
78
86
  debug(type, "↗️ sending message to tab", tabId, "frame", frameId);
79
87
  return browser.tabs.sendMessage(tabId, makeMessage(type, args, target, options), {
80
88
  frameId,
@@ -1,4 +1,11 @@
1
+ import { JsonObject } from "type-fest";
1
2
  import { Method } from "./types.js";
3
+ declare type ErrorObject = {
4
+ name?: string;
5
+ stack?: string;
6
+ message?: string;
7
+ code?: string;
8
+ } & JsonObject;
2
9
  export declare const __webextMessenger = true;
3
10
  export declare function isObject(value: unknown): value is Record<string, unknown>;
4
11
  export declare class MessengerError extends Error {
@@ -7,3 +14,6 @@ export declare class MessengerError extends Error {
7
14
  export declare const handlers: Map<string, Method>;
8
15
  export declare const debug: (...args: any[]) => void;
9
16
  export declare const warn: (...args: any[]) => void;
17
+ export declare function isErrorObject(error: unknown): error is ErrorObject;
18
+ export declare function delay(milliseconds: number): Promise<void>;
19
+ export {};
@@ -17,3 +17,13 @@ export const handlers = new Map();
17
17
  // .bind preserves the call location in the console
18
18
  export const debug = console.debug.bind(console, "Messenger:");
19
19
  export const warn = console.warn.bind(console, "Messenger:");
20
+ export function isErrorObject(error) {
21
+ var _a;
22
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- This is a type guard function and it uses ?.
23
+ return typeof ((_a = error) === null || _a === void 0 ? void 0 : _a.message) === "string";
24
+ }
25
+ export async function delay(milliseconds) {
26
+ return new Promise((resolve) => {
27
+ setTimeout(resolve, milliseconds);
28
+ });
29
+ }
@@ -1,6 +1,5 @@
1
- import { Target, PageTarget, MessengerMeta } from "./types.js";
2
- declare type AnyTarget = Partial<Target & PageTarget>;
3
- export declare function getActionForMessage(target: AnyTarget): "respond" | "forward" | "ignore";
1
+ import { AnyTarget, MessengerMeta, Sender } from "./types.js";
2
+ export declare function getActionForMessage(from: Sender, { ...to }: AnyTarget): "respond" | "forward" | "ignore";
4
3
  export declare function nameThisTarget(): Promise<void>;
5
4
  declare function __getTabData(this: MessengerMeta): AnyTarget;
6
5
  declare global {
@@ -1,4 +1,4 @@
1
- import { isBackgroundPage, isContentScript } from "webext-detect-page";
1
+ import { isBackgroundPage, isContentScript, isExtensionContext, } from "webext-detect-page";
2
2
  import { messenger } from "./sender.js";
3
3
  import { registerMethods } from "./receiver.js";
4
4
  import { debug } from "./shared.js";
@@ -6,9 +6,10 @@ import { debug } from "./shared.js";
6
6
  // This CANNOT be awaited because waiting for it means "I will handle the message."
7
7
  // If a message is received before this is ready, it will just have to be ignored.
8
8
  let thisTarget;
9
- //
10
- export function getActionForMessage(target) {
11
- if (target.page === "any") {
9
+ export function getActionForMessage(from, { ...to } // Clone object because we're editing it
10
+ ) {
11
+ var _a;
12
+ if (to.page === "any") {
12
13
  return "respond";
13
14
  }
14
15
  // Content scripts only receive messages that are meant for them. In the future
@@ -17,7 +18,7 @@ export function getActionForMessage(target) {
17
18
  return "respond";
18
19
  }
19
20
  // We're in an extension page, but the target is not one.
20
- if (!("page" in target)) {
21
+ if (!to.page) {
21
22
  return "forward";
22
23
  }
23
24
  if (!thisTarget) {
@@ -25,18 +26,24 @@ export function getActionForMessage(target) {
25
26
  // If this *was* the target, then probably no one else answered
26
27
  return "ignore";
27
28
  }
29
+ // If requests "this" tab, then set it to allow the next condition
30
+ if (to.tabId === "this" && thisTarget.tabId === ((_a = from.tab) === null || _a === void 0 ? void 0 : _a.id)) {
31
+ to.tabId = thisTarget.tabId;
32
+ }
28
33
  // Every `target` key must match `thisTarget`
29
- const isThisTarget = Object.entries(target).every(
34
+ const isThisTarget = Object.entries(to).every(
30
35
  // @ts-expect-error Optional properties
31
36
  ([key, value]) => thisTarget[key] === value);
32
37
  if (!isThisTarget) {
33
- debug("The message’s target is", target, "but this is", thisTarget);
38
+ debug("The message’s target is", to, "but this is", thisTarget);
34
39
  }
35
40
  return isThisTarget ? "respond" : "ignore";
36
41
  }
42
+ let nameRequested = false;
37
43
  export async function nameThisTarget() {
38
44
  // Same as above: CS receives messages correctly
39
- if (!thisTarget && !isContentScript()) {
45
+ if (!nameRequested && !thisTarget && !isContentScript()) {
46
+ nameRequested = true;
40
47
  thisTarget = await messenger("__getTabData", {}, { page: "any" });
41
48
  thisTarget.page = location.pathname;
42
49
  }
@@ -48,6 +55,9 @@ function __getTabData() {
48
55
  export function initPrivateApi() {
49
56
  if (isBackgroundPage()) {
50
57
  thisTarget = { page: "background" };
58
+ }
59
+ if (isExtensionContext()) {
60
+ // Any context can handler this message
51
61
  registerMethods({ __getTabData });
52
62
  }
53
63
  }
@@ -45,12 +45,17 @@ export declare type MessengerMessage = Message & {
45
45
  /** Guarantees that a message is meant to be handled by this library */
46
46
  __webextMessenger: true;
47
47
  };
48
+ export interface AnyTarget {
49
+ tabId?: number | "this";
50
+ frameId?: number;
51
+ page?: string;
52
+ }
48
53
  export interface Target {
49
54
  tabId: number;
50
55
  frameId?: number;
51
56
  }
52
57
  export interface PageTarget {
53
- tabId?: number;
58
+ tabId?: number | "this";
54
59
  page: string;
55
60
  }
56
61
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webext-messenger",
3
- "version": "0.15.0-1",
3
+ "version": "0.15.0-5",
4
4
  "description": "Browser Extension component messaging framework",
5
5
  "keywords": [],
6
6
  "repository": "pixiebrix/webext-messenger",