Module: messaging

This module provides functionality for passing messages between the background page and content script environments. Messages between the environments are easily malformed, and minor errors in message handlers can have cascading effects. These problems can be quite difficult to debug. This module addresses these issues by providing a simple message type and type checking system on top of browser.runtime.onMessage and browser.tabs.sendMessage.

Messages

A message, for purposes of this module, must be an object and must have a type property with a string value.

Schemas

A schema, for purposes of this module, must be an object. Each property in the schema object is a property that is required in a corresponding message object. Each value in the schema object is a string that must match the typeof value for that property in a corresponding message.

Source:

Namespaces

onMessage

Methods

(static) registerSchema(messageType, messageSchema)

Registers a schema for a type of message.

Parameters:
Name Type Description
messageType string

The type of message that must follow the schema.

messageSchema Object

An object where each field has a value that is a built-in type string.

Source:

(static) sendMessageToTab(tabId, message) → {Promise}

Sends a message to a tab after checking the message against the registered schema for the message type. Equivalent to calling browser.tabs.sendMessage with a catch handler after validating the message against the schema.

Parameters:
Name Type Description
tabId number

The ID of the tab that should receive the message.

message Object

The contents of the message.

Source:
Returns:
  • The same return value as browser.tabs.sendMessage, or a Promise that resolves to false if there was an errror sending the message.
Type
Promise

(static) unregisterSchema(messageType)

Unregisters a schema for a type of message, if one is registered.

Parameters:
Name Type Description
messageType string

The type of message .

Source: