Communicate Across the DOM

The easiest way to communicate between components that aren’t in the same DOM tree is to use Lightning message service (lightning/messageService). Consider using the publish-subscribe mechanism with the pubsub module only if you’re working in containers that don’t support Lightning Message Service. The pubsub module is no longer officially supported or actively maintained.

Use Lightning Message Service 

To communicate between components in a single Lightning page or across multiple pages, set up a Lightning message channel. The advantage over the publish-subscribe mechanism is that message channels aren’t restricted to a single page. Any component in a Lightning Experience application that listens for events on a message channel updates when it receives a message. It works between Lightning web components, Aura components, and Visualforce pages in any tab or in any pop-out window in Lightning Experience. It also works across namespaces.

To use Lightning Message Service:

  1. Declare a message channel using the LightningMessageChannel metadata type.
  2. Publish a message using the publish() function from the @salesforce/messageChannel module.
  3. Subscribe and unsubscribe to a message using the subscribe() and unsubscribe() functions from the @salesforce/messageChannel module.

Use the pubsub Module 

In containers that don’t support Lightning Messaging Service, use the pubsub module. Download the module from github.com/developerforce/pubsub.

In a publish-subscribe pattern, one component publishes an event. Other components subscribe to receive and handle the event. Every component that subscribes to the event receives the event. The pubsub module restricts events to a single page. You must also manually unregister all components that are registered to pubsub.

The pubsub module is not officially supported or actively maintained.

Note

See Also

Release Preview

This release is in preview. Features described here don't become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can't guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.