Sub topic 9
Default scope versus APPLICATION_SCOPE
This chapter assumes you can already publish and subscribe in a Lightning web component (LWC). It also assumes you know how connectedCallback and disconnectedCallback work and how components are placed on Lightning pages and in apps. Here you will learn which subscribers receive a message and how the scope option changes that.
Why scope exists
A message channel has no built-in idea of "nearby" components. Any component that subscribes to the channel is a candidate recipient. Lightning Experience can keep many pages alive at once, though. A console app can have a dozen open workspace tabs, and each tab holds its own components. Without a rule, a message published in one tab would reach every subscriber in all the others.
Scope is that rule. It is set by the subscriber, not the publisher. The publisher calls publish the same way every time and never says who should receive the message. Each subscriber decides how far away a message may come from.
The two scopes
There are two behaviors:
- Default scope. The subscriber receives messages only while it is in the active area of the application. The active area is the tab or navigation item the user is currently viewing.
- APPLICATION_SCOPE. The subscriber receives messages published from anywhere in the application, including from tabs and navigation items that are not currently active.
You choose APPLICATION_SCOPE by importing the constant from lightning/messageService and passing it in the options object, which is the fourth argument of subscribe. If you omit the options object, you get the default scope.
import { LightningElement, wire } from 'lwc';
import {
subscribe,
unsubscribe,
APPLICATION_SCOPE,
MessageContext
} from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
export default class ScopeDemo extends LightningElement {
defaultSubscription = null;
applicationSubscription = null;
lastDefault;
lastApplication;
@wire(MessageContext)
messageContext;
connectedCallback() {
// Default scope: only messages while this component's tab is active.
this.defaultSubscription = subscribe(
this.messageContext,
RECORD_SELECTED,
(message) => {
this.lastDefault = message.recordId;
}
);
// Application scope: messages from anywhere in the application.
this.applicationSubscription = subscribe(
this.messageContext,
RECORD_SELECTED,
(message) => {
this.lastApplication = message.recordId;
},
{ scope: APPLICATION_SCOPE }
);
}
disconnectedCallback() {
unsubscribe(this.defaultSubscription);
unsubscribe(this.applicationSubscription);
this.defaultSubscription = null;
this.applicationSubscription = null;
}
}This component subscribes twice on purpose, so you can see the difference. Put it on a page in a console app with two workspace tabs. Publish from the other tab, and only lastApplication changes. Publish from the tab the component sits in, and both fields change.
Each call to subscribe returns its own subscription object, so each one needs its own unsubscribe. Subscribing twice to the same channel is not a mistake here, but in real code you rarely need both.
How delivery is decided
For each subscriber, the framework asks two questions when a message is published. The diagram shows the order.
Two details follow from this:
- Delivery is evaluated at publish time. A subscriber that was in an inactive tab with default scope does not get a queued copy when the user returns to its tab. The message is simply missed.
- Scope only restricts delivery. It never adds subscribers. A component that has not called
subscribereceives nothing under either scope.
Where the difference shows up
In a standard navigation app, the user sees one page at a time. A single record page usually has all its components in the active area, so default scope and APPLICATION_SCOPE behave the same for components on that page. The difference matters in these cases:
| Situation | Default scope | APPLICATION_SCOPE |
|---|---|---|
| Publisher and subscriber on the same visible page | Delivered | Delivered |
| Console app, publisher in the active tab, subscriber in a background tab | Not delivered | Delivered |
| Console app, two tabs showing different records, both with the same component | Each component hears only messages while its tab is active | Each component hears messages from both tabs |
| Subscriber on a page the user has navigated away from, still alive in the app | Not delivered | Delivered |
The third row is the one that causes trouble, and it is covered below.
Other surfaces, such as the utility bar, count as separate areas of the application. Their exact active-area behavior is easy to get wrong, so confirm it in a test org for your app type. Do not assume it.
Choosing a scope
Start from where your subscribers live, not from what feels safest.
Use the default scope when:
- Publisher and subscribers are always on the same page and shown together.
- You want a component in a hidden tab to ignore messages. A list in one tab should not move the detail view in another tab.
- The subscriber does expensive work in its handler, such as an Apex call. Background tabs should not run that work for messages the user cannot see.
Use APPLICATION_SCOPE when:
- The subscriber lives somewhere that is not in the active area when the message is published. A common case is a utility bar component that reacts to a record selection in the main page.
- The user can change tabs between the action and the reaction, and the reaction still has to happen. For example, a background tab should refresh its data after an update from another tab.
- The publisher is in one navigation item and the subscriber is in another.
A practical rule: if you can write down a case where publisher and subscriber are not visible together, you need APPLICATION_SCOPE. If you cannot, default scope is enough and is less likely to produce surprises.
Handling cross-tab messages safely
APPLICATIONSCOPE trades isolation for reach. Imagine a console app with two tabs, each showing a different Account. Each tab has a RecordDetail component subscribed with APPLICATIONSCOPE. When the user selects a record in tab A, the detail component in tab B also receives the message and changes what it shows. The user returns to tab B and finds it displaying the wrong record.
The fix is to put enough information in the payload for the subscriber to decide whether the message is meant for it, and to filter in the handler.
import { LightningElement, api, wire } from 'lwc';
import {
subscribe,
unsubscribe,
APPLICATION_SCOPE,
MessageContext
} from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
export default class FilteredDetail extends LightningElement {
// Set automatically when the component sits on a record page.
@api recordId;
selectedId;
subscription = null;
@wire(MessageContext)
messageContext;
connectedCallback() {
if (!this.subscription) {
this.subscription = subscribe(
this.messageContext,
RECORD_SELECTED,
(message) => this.handleMessage(message),
{ scope: APPLICATION_SCOPE }
);
}
}
disconnectedCallback() {
unsubscribe(this.subscription);
this.subscription = null;
}
handleMessage(message) {
// Ignore messages about a different parent record.
if (message.parentId && message.parentId !== this.recordId) {
return;
}
this.selectedId = message.recordId;
}
}This version expects the payload to carry a parentId field next to recordId. For that to work, the channel metadata must declare both fields and the publisher must send both. The extra field is a small cost, and it keeps one tab from overwriting another.
Scope and subscription lifecycle
Scope and lifecycle are separate concerns, and mixing them up leads to bugs.
- A component with default scope that sits in a background tab is still connected and still subscribed. It is simply not eligible to receive messages until its area becomes active. You do not need to unsubscribe when the tab goes inactive.
- A component with APPLICATIONSCOPE keeps receiving messages for as long as it is subscribed, which is until you call
unsubscribeor the component is removed. Forgetting to unsubscribe indisconnectedCallbackcosts more under APPLICATIONSCOPE, because a stale handler can fire from anywhere in the app. - Changing scope means subscribing again. The scope is fixed in the subscription. To switch, unsubscribe and call
subscribewith the new options.
Scope in Aura and Visualforce
The same two behaviors exist outside LWC, with different syntax.
In Aura, the lightning:messageChannel tag takes a scope attribute. Setting scope="APPLICATION" gives application-wide delivery. Leaving it off gives the default behavior.
<lightning:messageChannel
type="RecordSelected__c"
aura:id="recordSelectedChannel"
onMessage="{!c.handleMessage}"
scope="APPLICATION"/>Visualforce pages pass the scope in the options object when subscribing through sforce.one.subscribe. The value is the string "APPLICATION", as in { scope: "APPLICATION" }. Later chapters cover the Visualforce setup in full. The point here is that all three technologies share the same two scopes, so a mixed page behaves consistently when each subscriber states its scope.
Common errors
- A subscriber works on a record page but not in a console tab. The publisher is in another tab and the subscriber used default scope. Add
{ scope: APPLICATION_SCOPE }. - Messages from one tab change another tab. The subscriber uses APPLICATION_SCOPE with no filter. Add an identifying field to the payload and check it in the handler.
- Passing the scope as the third argument. The third argument is the callback. The options object is fourth. A misplaced object leaves you with default scope or a broken call.
- Importing from the wrong place.
APPLICATION_SCOPEcomes fromlightning/messageService, not fromlwcor the channel import. - Unsubscribing only one of several subscriptions. Each
subscribecall needs its ownunsubscribe.
Exercise
A console app has two workspace tabs. A RecordList component in tab A publishes on RecordSelected__c. A RecordDetail component in tab B subscribes with subscribe(this.messageContext, RECORD_SELECTED, handler). The user clicks a record in tab A, then switches to tab B. The detail component shows nothing. Why, and what is the smallest change that fixes it?
Show answer
Without an options object, the subscriber uses default scope, so it only receives messages while its own tab is active. Tab B was inactive when the message was published, and the message is not queued. Add { scope: APPLICATION_SCOPE } as the fourth argument, importing APPLICATION_SCOPE from lightning/messageService.
Exercise
After you switch the detail component to APPLICATION_SCOPE, a second tab with another RecordDetail instance starts showing records chosen in the first tab. Name two changes, one to the payload and one to the subscriber, that stop this.
Show answer
Add a field such as parentId to the channel's lightningMessageFields and include it in the payload when publishing. In the subscriber's handler, compare message.parentId with the component's own recordId and return early when they differ.