Publish on a Message Channel

To publish messages on a message channel from a Lightning web component, include the @salesforce/messageChannel scoped module in your component's JavaScript file and call the Lightning message service’s publish() function.

The Lightning message service publishes messages to any subscribed component until the destroy phase of the component lifecycle. Sometimes when you navigate away from a Lightning page, components are cached and not destroyed. If the Lightning message service is scoped to the entire application, these components still publish to and receive messages from the Lightning message service.

The lwc-recipes repo has an lmsPublisherWebComponent component that publishes a message to notify subscribers on a Lightning page. The Lightning message service communicates that message across Visualforce, Aura, and Lightning Web components on the page.

Publisher components for LWC, Aura, and Visualforce

Let's take a look at the lmsPublisherWebComponent component. The component's HTML template file displays a list of contacts. When a contact is selected, the handleContactSelect handler is invoked, which publishes a message to the message channel.

In your component's JavaScript file, import the message channel and the Lightning message service functions necessary for working with a message channel.

Use @wire(MessageContext) to create a MessageContext object, which provides information about the Lightning web component that is using the Lightning message service. When using the @wire(MessageContext) adapter, you don’t have to interact with any of the component’s lifecycle events. The Lightning message service features automatically unregister when the component is destroyed.

The handleContactSelect() method creates the message content to publish. The Lightning message service's publish() function takes three parameters, the message context, the name of the message channel, and the message payload. Here, the message payload is a JSON object where the recordId key has the value event.target.contact.Id.

A component must be attached to the DOM before it can use the property decorated with @wire(MessageContext). You can’t use @wire(MessageContext) in a constructor() function.

See Also