Message Service

lightning/messageService

Enables communication across different types of pages.

For Use In

Lightning Experience, Experience Builder Sites, Salesforce Mobile App

Use Lightning message service to communicate across the DOM between Visualforce pages, Aura components, and Lightning web components, including components in a pop-out utility bar.

Use the Lightning message service functions to communicate over a Lightning message channel.

In a component’s Javascript file, import the functions you need from the lightning/messageService module. Import a message channel using the scoped module @salesforce/messageChannel.

1import {
2  APPLICATION_SCOPE,
3  createMessageContext,
4  MessageContext,
5  publish,
6  releaseMessageContext,
7  subscribe,
8  unsubscribe,
9} from "lightning/messageService";
10import recordSelected from "@salesforce/messageChannel/Record_Selected__c";

createMessageContext() 

Returns a MessageContext object.

Call this function in a service component that doesn’t extend LightningElement. In a service component, you can’t use @wire(MessageContext) to create a MessageContext object. Instead, call the createMessageContext() function to create the MessageContext object and assign it to a field, like messageContext. Then, pass messageContext into the subscribe() function. MessageContext isn’t automatically released for service components. Call releaseMessageContext(messageContext) to remove any subscriptions associated with your Lightning web component’s MessageContext.

publish(messageContext, messageChannel, message) 

Publishes a message to a specified message channel.

ParameterTypeDescription
messageContextobjectThe MessageContext object provides information about the Lightning web component that is using the Lightning message service. Get this object via the MessageContext wire adapter or via createMessageContext().
messageChannelobjectThe message channel object. To import a message channel, use the scoped module @salesforce/messageChannel. To create a message channel in an org, use the LightningMessageChannel metadata type.
messageobjectA serializable JSON object containing the message published to subscribers. A message can’t contain functions or symbols.

releaseMessageContext(messageContext) 

Releases a MessageContext object associated with a Lightning web component and unsubscribes all associated subscriptions.

subscribe(messageContext, messageChannel, listener, subscriberOptions) 

Subscribes to a specified message channel. Returns a Subscription object that you can use to unsubscribe.

By default, communication over a message channel can occur only between Lightning web components, Aura components, or Visualforce pages in an active navigation tab, an active navigation item, or a utility item. Utility items are always active. A navigation tab or item is active when it’s selected. Navigation tabs and items include:

  • Standard navigation tabs
  • Console navigation workspace tabs
  • Console navigation subtabs
  • Console navigation items

To receive messages on a message channel from anywhere in the application, pass the subscriberOptions parameter as {scope: APPLICATION_SCOPE}. Import APPLICATION_SCOPE from lightning/messageService.

ParameterTypeDescription
messageContextobjectThe MessageContext object provides information about the Lightning web component that is using the Lightning message service.
messageChannelobjectTo import a message channel, use the scoped module @salesforce/messageChannel. To create a message channel in an org, use the LightningMessageChannel metadata type.
listenerfunctionA function that handles the message once it is published.
subscriberOptionsobject(Optional) An object that, when set to {scope: APPLICATION_SCOPE}, specifies the ability to receive messages on a message channel from anywhere in the application. Import APPLICATION_SCOPE from lightning/messageService.

unsubscribe(subscription) 

Unsubscribes from a message channel.

ParameterTypeDescription
subscriptionobjectThe Subscription object returned by the subscribe() function.

MessageContext Wire Adapter 

Returns a MessageContext object.

The MessageContext object contains information about the Lightning web component that is using the Lightning message service. Pass the MessageContext object to the publish() and subscribe() functions. 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.

1@wire(MessageContext)
2    messageContext;

Usage 

These two components publish a message and subscribe to the message over the same message channel.

1// lmsPublisherWebComponent.js
2import { LightningElement, wire } from "lwc";
3import getContactList from "@salesforce/apex/ContactController.getContactList";
4
5// Import message service features required for publishing and the message channel
6import { publish, MessageContext } from "lightning/messageService";
7import recordSelected from "@salesforce/messageChannel/Record_Selected__c";
8
9export default class LmsPublisherWebComponent extends LightningElement {
10  @wire(getContactList)
11  contacts;
12
13  @wire(MessageContext)
14  messageContext;
15
16  // Respond to UI event by publishing message
17  handleContactSelect(event) {
18    const payload = { recordId: event.target.contact.Id };
19
20    publish(this.messageContext, recordSelected, payload);
21  }
22}
1// lmsSubscriberWebComponent.js
2import { LightningElement, wire } from "lwc";
3import { getRecord, getFieldValue } from "lightning/uiRecordApi";
4import { ShowToastEvent } from "lightning/platformShowToastEvent";
5import { reduceErrors } from "c/ldsUtils";
6
7// Import message service features required for subscribing and the message channel
8import {
9  subscribe,
10  unsubscribe,
11  APPLICATION_SCOPE,
12  MessageContext,
13} from "lightning/messageService";
14import recordSelected from "@salesforce/messageChannel/Record_Selected__c";
15
16import NAME_FIELD from "@salesforce/schema/Contact.Name";
17import TITLE_FIELD from "@salesforce/schema/Contact.Title";
18import PHONE_FIELD from "@salesforce/schema/Contact.Phone";
19import EMAIL_FIELD from "@salesforce/schema/Contact.Email";
20import PICTURE_FIELD from "@salesforce/schema/Contact.Picture__c";
21
22const fields = [NAME_FIELD, TITLE_FIELD, PHONE_FIELD, EMAIL_FIELD, PICTURE_FIELD];
23
24export default class LmsSubscriberWebComponent extends LightningElement {
25  subscription = null;
26  recordId;
27
28  Name;
29  Title;
30  Phone;
31  Email;
32  Picture__c;
33
34  @wire(getRecord, { recordId: "$recordId", fields })
35  wiredRecord({ error, data }) {
36    if (error) {
37      this.dispatchToast(error);
38    } else if (data) {
39      fields.forEach((item) => (this[item.fieldApiName] = getFieldValue(data, item)));
40    }
41  }
42
43  @wire(MessageContext)
44  messageContext;
45
46  // Encapsulate logic for Lightning message service subscribe and unsubsubscribe
47  subscribeToMessageChannel() {
48    if (!this.subscription) {
49      this.subscription = subscribe(
50        this.messageContext,
51        recordSelected,
52        (message) => this.handleMessage(message),
53        { scope: APPLICATION_SCOPE },
54      );
55    }
56  }
57
58  unsubscribeToMessageChannel() {
59    unsubscribe(this.subscription);
60    this.subscription = null;
61  }
62
63  // Handler for message received by component
64  handleMessage(message) {
65    this.recordId = message.recordId;
66  }
67
68  // Standard lifecycle hooks used to subscribe and unsubsubscribe to the message channel
69  connectedCallback() {
70    this.subscribeToMessageChannel();
71  }
72
73  disconnectedCallback() {
74    this.unsubscribeToMessageChannel();
75  }
76
77  // Helper
78  dispatchToast(error) {
79    this.dispatchEvent(
80      new ShowToastEvent({
81        title: "Error loading contact",
82        message: reduceErrors(error).join(", "),
83        variant: "error",
84      }),
85    );
86  }
87}

LWC Recipes 

The LWC Recipes GitHub repository contains code examples for Lightning Web Components that you can test in an org.

For a recipe that uses lightning/messageService, see the following components in the LWC Recipes repo.

  • c-lms-publisher-web-component
  • c-lms-subscriber-web-component

See Also 

Lightning Web Components Developer Guide: Communicate Across the DOM with Lightning Message Service

error fallback image
No specifications to show
No specifications are available for this component or API module. When specifications are defined, they'll appear here.