WebExt Core
Messaging

Api


description: ""

See @webext-core/messaging

BaseMessagingConfig

interface BaseMessagingConfig {
  logger?: Logger;
  breakError?: boolean;
}

Shared configuration between all the different messengers.

Properties

  • logger?: Logger (default: console)
    The logger to use when logging messages. Set to null to disable logging.
  • breakError?: boolean (default: undefined)
    Whether to break an error when an invalid message is received.

CustomEventMessage

interface CustomEventMessage {
  event: CustomEvent;
}

Additional fields available on the Message from a CustomEventMessenger.

Properties

  • event: CustomEvent
    The event that was fired, resulting in the message being passed.

CustomEventMessagingConfig

interface CustomEventMessagingConfig extends NamespaceMessagingConfig {}

Configuration passed into defineCustomEventMessaging.

CustomEventMessenger

type CustomEventMessenger<TProtocolMap extends Record<string, any>> =
  GenericMessenger<TProtocolMap, CustomEventMessage, []>;

Messenger returned by defineCustomEventMessenger.

defineCustomEventMessaging

function defineCustomEventMessaging<
  TProtocolMap extends Record<string, any> = Record<string, any>,
>(config: CustomEventMessagingConfig): CustomEventMessenger<TProtocolMap> {
  // ...
}

Creates a CustomEventMessenger. This messenger is backed by the CustomEvent APIs. It can be used to communicate between:

  • Content script and website
  • Content script and injected script

sendMessage does not accept any additional arguments..

Examples

interface WebsiteMessengerSchema {
  initInjectedScript(data: ...): void;
}

export const websiteMessenger = defineCustomEventMessenger<initInjectedScript>();

// Content script
websiteMessenger.sendMessage("initInjectedScript", ...);

// Injected script
websiteMessenger.onMessage("initInjectedScript", (...) => {
  // ...
})

*

defineExtensionMessaging

function defineExtensionMessaging<
  TProtocolMap extends Record<string, any> = Record<string, any>,
>(config?: ExtensionMessagingConfig): ExtensionMessenger<TProtocolMap> {
  // ...
}

Returns an ExtensionMessenger that is backed by the browser.runtime.sendMessage and browser.tabs.sendMessage APIs.

It can be used to send messages to and from the background page/service worker.

defineWindowMessaging

function defineWindowMessaging<
  TProtocolMap extends Record<string, any> = Record<string, any>,
>(config: WindowMessagingConfig): WindowMessenger<TProtocolMap> {
  // ...
}

Returns a WindowMessenger. It is backed by the window.postMessage API. It can be used to communicate between:

  • Content script and website
  • Content script and injected script

Examples

interface WebsiteMessengerSchema {
  initInjectedScript(data: ...): void;
}

export const websiteMessenger = defineWindowMessaging<initInjectedScript>();

// Content script
websiteMessenger.sendMessage("initInjectedScript", ...);

// Injected script
websiteMessenger.onMessage("initInjectedScript", (...) => {
  // ...
})

ExtensionMessage

interface ExtensionMessage {
  sender: Runtime.MessageSender;
}

Additional fields available on the Message from an ExtensionMessenger.

Properties

ExtensionMessagingConfig

interface ExtensionMessagingConfig extends BaseMessagingConfig {}

Configuration passed into defineExtensionMessaging.

ExtensionMessenger

type ExtensionMessenger<TProtocolMap extends Record<string, any>> =
  GenericMessenger<TProtocolMap, ExtensionMessage, ExtensionSendMessageArgs>;

Messenger returned by defineExtensionMessaging.

ExtensionSendMessageArgs

type ExtensionSendMessageArgs = [arg?: number | SendMessageOptions];

Send message accepts either:

  • No arguments to send to background
  • A tabId number to send to a specific tab
  • A SendMessageOptions object to target a specific tab and frame

You cannot message between tabs directly. It must go through the background script.

GenericMessenger

interface GenericMessenger<
  TProtocolMap extends Record<string, any>,
  TMessageExtension,
  TSendMessageArgs extends any[],
> {
  sendMessage<TType extends keyof TProtocolMap>(
    type: TType,
    ...args: GetDataType<TProtocolMap[TType]> extends undefined
      ? [data?: undefined, ...args: TSendMessageArgs]
      : never
  ): Promise<GetReturnType<TProtocolMap[TType]>>;
  sendMessage<TType extends keyof TProtocolMap>(
    type: TType,
    data: GetDataType<TProtocolMap[TType]>,
    ...args: TSendMessageArgs
  ): Promise<GetReturnType<TProtocolMap[TType]>>;
  onMessage<TType extends keyof TProtocolMap>(
    type: TType,
    onReceived: (
      message: Message<TProtocolMap, TType> & TMessageExtension,
    ) => void | MaybePromise<GetReturnType<TProtocolMap[TType]>>,
  ): RemoveListenerCallback;
  removeAllListeners(): void;
}

Messaging interface shared by all messengers.

Type parameters accept:

  • TProtocolMap to define the data and return types of messages.
  • TMessageExtension to define additional fields that are available on a message inside onMessage's callback
  • TSendMessageArgs to define a list of additional arguments for sendMessage

GetDataType

type GetDataType<T> = T extends (...args: infer Args) => any
  ? Args["length"] extends 0 | 1
    ? Args[0]
    : never
  : T extends ProtocolWithReturn<any, any>
    ? T["BtVgCTPYZu"]
    : T;

Given a function declaration, ProtocolWithReturn, or a value, return the message's data type.

GetReturnType

type GetReturnType<T> = T extends (...args: any[]) => infer R
  ? R
  : T extends ProtocolWithReturn<any, any>
    ? T["RrhVseLgZW"]
    : void;

Given a function declaration, ProtocolWithReturn, or a value, return the message's return type.

Logger

interface Logger {
  debug(...args: any[]): void;
  log(...args: any[]): void;
  warn(...args: any[]): void;
  error(...args: any[]): void;
}

Interface used to log text to the console when sending and receiving messages.

MaybePromise

type MaybePromise<T> = Promise<T> | T;

Either a Promise of a type, or that type directly. Used to indicate that a method can by sync or async.

Message

interface Message<
  TProtocolMap extends Record<string, any>,
  TType extends keyof TProtocolMap,
> {
  id: number;
  data: GetDataType<TProtocolMap[TType]>;
  type: TType;
  timestamp: number;
}

Contains information about the message received.

Properties

  • id: number
    A semi-unique, auto-incrementing number used to trace messages being sent.
  • data: GetDataType<TProtocolMap[TType]>
    The data that was passed into sendMessage
  • type: TType
  • timestamp: number
    The timestamp the message was sent in MS since epoch.

NamespaceMessagingConfig

interface NamespaceMessagingConfig extends BaseMessagingConfig {
  namespace: string;
}

Properties

  • namespace: string
    A string used to ensure the messenger only sends messages to and listens for messages from other messengers of the same type, with the same namespace.

ProtocolWithReturn

:::danger Deprecated Use the function syntax instead: https://webext-core.aklinker1.io/messaging/protocol-maps.html#syntax :::

interface ProtocolWithReturn<TData, TReturn> {
  BtVgCTPYZu: TData;
  RrhVseLgZW: TReturn;
}

Used to add a return type to a message in the protocol map.

Internally, this is just an object with random keys for the data and return types.

Properties

  • BtVgCTPYZu: TData
    Stores the data type. Randomly named so that it isn't accidentally implemented.
  • RrhVseLgZW: TReturn
    Stores the return type. Randomly named so that it isn't accidentally implemented.

Examples

interface ProtocolMap {
  // data is a string, returns undefined
  type1: string;
  // data is a string, returns a number
  type2: ProtocolWithReturn<string, number>;
}

RemoveListenerCallback

type RemoveListenerCallback = () => void;

Call to ensure an active listener has been removed.

If the listener has already been removed with Messenger.removeAllListeners, this is a noop.

SendMessageOptions

interface SendMessageOptions {
  tabId: number;
  frameId?: number;
}

Options for sending a message to a specific tab/frame

Properties

  • tabId: number
    The tab to send a message to
  • frameId?: number
    The frame to send a message to. 0 represents the main frame.

WindowMessagingConfig

interface WindowMessagingConfig extends NamespaceMessagingConfig {}

Configuration passed into defineWindowMessaging.

WindowMessenger

type WindowMessenger<TProtocolMap extends Record<string, any>> =
  GenericMessenger<TProtocolMap, {}, WindowSendMessageArgs>;

WindowSendMessageArgs

type WindowSendMessageArgs = [targetOrigin?: string];

For a WindowMessenger, sendMessage requires an additional argument, the targetOrigin. It defines which frames inside the page should receive the message.

See https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#targetorigin for more details.




API reference generated by docs/generate-api-references.ts