Sub topic 11
Bridging LWC, Aura, and Visualforce
This chapter assumes you can already publish and subscribe from a Lightning web component (LWC). It also assumes you have deployed a message channel and know what scope does. If not, review those chapters first. Here the same channel is used from two other technologies, and you will see where they differ.
Why one channel can serve three technologies
A message channel is metadata, not code. It does not belong to LWC. Lightning Message Service (LMS) exposes the channel through a different API in each technology:
| Technology | Channel reference | Publish | Subscribe |
|---|---|---|---|
| LWC | `import ... from '@salesforce/messageChannel/RecordSelected__c'` | `publish()` from `lightning/messageService` | `subscribe()` from `lightning/messageService` |
| Aura | `type="RecordSelected__c"` on `lightning:messageChannel` | `publish()` method on the tag's component reference | `onMessage` handler on the tag |
| Visualforce | `{!$MessageChannel.RecordSelected__c}` merge field | `sforce.one.publish()` | `sforce.one.subscribe()` |
All three refer to the channel by the same API name, which ends in __c. A message published by one is delivered to subscribers in the others, provided the scope rules allow it.
The block above is not a diagram. The real diagram follows.
Requirements that apply to every technology
Check these before you debug anything else.
- The channel must have
<isExposed>true</isExposed>. Aura and Visualforce cannot reach a channel that is not exposed. - The channel must be deployed to the org. Aura and Visualforce reference it by name at runtime.
- LMS works in Lightning Experience. A Visualforce page opened in Salesforce Classic has no
sforce.oneto talk to. - Publisher and subscriber must be on the same Lightning page, or in the same app for subscribers that use application scope.
- The payload is a plain, serializable object. Keep the same field names on both sides.
recordIdis not the same asrecordID.
Using the channel from Aura
An Aura component listens with the lightning:messageChannel tag. This is the markup from the plan:
<aura:component implements="flexipage:availableForAllPageTypes">
<aura:attribute name="selectedId" type="String"/>
<lightning:messageChannel
type="RecordSelected__c"
aura:id="recordSelectedChannel"
onMessage="{!c.handleMessage}"
scope="APPLICATION"/>
<p>Selected: {!v.selectedId}</p>
</aura:component>The controller reads the payload with getParam:
({
handleMessage: function (component, message) {
if (message != null && message.getParam('recordId') != null) {
component.set('v.selectedId', message.getParam('recordId'));
}
}
})Four details matter here.
- No subscription code. The framework subscribes when the component is created and unsubscribes when it is destroyed. You do not write
connectedCallbackordisconnectedCallbacklogic as you do in LWC. scope="APPLICATION"is the Aura equivalent ofAPPLICATION_SCOPE. If you leave it out, the component receives messages only while it is active in its own context. A component on a different tab or in the utility bar will not hear a publisher that uses a different context.- The handler gets a message object, not a payload. In LWC,
message.recordIdis a property. In Aura, you callmessage.getParam('recordId'). Mixing these up gives youundefined. - The null check is deliberate. The handler can run with a message that has no
recordId, for example if another publisher sends a different payload shape. Without the check,component.setwould overwrite good state withundefined.
Publishing from Aura
The same tag can publish. Call the publish method on the component reference you get from aura:id.
({
handleSelect: function (component, event, helper) {
const payload = { recordId: event.currentTarget.dataset.id };
component.find('recordSelectedChannel').publish(payload);
}
})This works only if the component's markup includes the lightning:messageChannel tag with that aura:id. The tag is both the subscription and the publishing handle. If the component should only publish, you can omit onMessage, but then it still needs the tag.
A component that both publishes and subscribes will receive its own message. Guard against this by including a sender identifier in the payload, or by comparing the incoming value with the current state before acting.
Using the channel from Visualforce
Visualforce has no tag for LMS. You use the sforce.one JavaScript object that Lightning Experience injects into the page. The channel is referenced through the $MessageChannel merge field, which the server resolves when the page renders.
<apex:page>
<div>
<p>Selected: <span id="selected">none</span></p>
<button onclick="subscribeToChannel()">Subscribe</button>
<button onclick="unsubscribeFromChannel()">Unsubscribe</button>
<button onclick="publishMessage()">Publish</button>
</div>
<script>
const RECORD_SELECTED = "{!$MessageChannel.RecordSelected__c}";
let subscriptionId = null;
function subscribeToChannel() {
if (!subscriptionId) {
subscriptionId = sforce.one.subscribe(
RECORD_SELECTED,
onMessage,
{ scope: "APPLICATION" }
);
}
}
function unsubscribeFromChannel() {
if (subscriptionId) {
sforce.one.unsubscribe(subscriptionId);
subscriptionId = null;
}
}
function onMessage(message) {
document.getElementById("selected").textContent = message.recordId;
}
function publishMessage() {
sforce.one.publish(RECORD_SELECTED, { recordId: "001000000000001AAA" });
}
</script>
</apex:page>Compared with LWC, note these differences.
- The listener receives the payload directly.
message.recordIdworks, as in LWC. Aura is the odd one out. - You manage the subscription yourself.
sforce.one.subscribereturns an ID. Keep it, and pass it tosforce.one.unsubscribewhen you no longer need the messages. A Visualforce page has no component lifecycle hooks, so decide where the cleanup belongs. Typical choices are a button, a page event, or abeforeunloadhandler. - The options object is the third argument.
{ scope: "APPLICATION" }takes a string, not an imported constant. - The channel value is a string. The merge field resolves to the fully qualified channel name. Do not hard-code the name yourself. Use the merge field so that a namespace prefix in a packaged org is handled for you.
- The page must run inside Lightning Experience. Opening the Visualforce page directly by URL, outside a Lightning page, leaves
sforce.oneundefined or inert.
Mixing the three on one page
Suppose a Lightning record page contains an LWC list, an Aura detail card, and a Visualforce history panel. All three use RecordSelected__c.
- The LWC list publishes
{ recordId }withpublish(this.messageContext, RECORD_SELECTED, payload). - The Aura card subscribes with
scope="APPLICATION"and readsmessage.getParam('recordId'). - The Visualforce panel subscribes through
sforce.one.subscribewith{ scope: "APPLICATION" }and readsmessage.recordId.
Nothing in the LWC changes when you add the other two. That is the benefit of the contract: the publisher does not know who listens.
Choosing the scope per technology
| Situation | Scope to use |
|---|---|
| Publisher and subscriber are both in the same active page region and tab | Default scope is enough |
| Subscriber is in a utility bar, a different tab, or a different region | Application scope |
| Visualforce subscriber that must hear LWC or Aura publishers | Application scope, passed in the options object |
| Aura subscriber that must hear anything outside its own context | `scope="APPLICATION"` on the tag |
If you are unsure, test with application scope first, then narrow it. A subscriber that is too narrow fails silently, so it is the harder mistake to notice.
Common errors
- Aura handler reads
message.recordId. The value isundefined. Usemessage.getParam('recordId'). - Visualforce page shows nothing. Check that the page is inside a Lightning page and that the browser console shows no
sforce.one is undefinederror. - Aura component never fires
onMessage. Check thatscope="APPLICATION"is set when the publisher is elsewhere, and that the channel API name ends in__cin thetypeattribute. - Channel works in LWC but not elsewhere. Check
isExposed. LWC in the same namespace can sometimes work in cases where Aura and Visualforce do not, so a test that passes in LWC does not prove the channel is exposed. - Duplicate messages in Visualforce.
subscribewas called twice and the first ID was lost. Guard withif (!subscriptionId), as in the example above. - Payload mismatch. A publisher renames
recordIdtoid. All subscribers receiveundefinedfor the old name. Treat the field list in the channel metadata as the shared contract and change it deliberately.
Exercise
An Aura component subscribes to RecordSelected__c with scope="APPLICATION". Its controller contains component.set('v.selectedId', message.recordId);. An LWC publishes { recordId: "001xx" }, and the handler runs, but selectedId stays empty. What is wrong, and how do you fix it? Then state how a Visualforce subscriber on the same page would read the same value.
Show answer
Aura passes a message object, not the raw payload, so message.recordId is undefined. Use message.getParam('recordId'), ideally guarded with a null check. A Visualforce listener passed to sforce.one.subscribe receives the payload directly, so it reads message.recordId.
Exercise
A Visualforce page calls sforce.one.subscribe(RECORD_SELECTED, onMessage, { scope: "APPLICATION" }) every time the user clicks a button, and the user later sees each message handled three times. What caused this, and what two changes prevent it?
Show answer
Each click creates a new subscription, and the earlier subscription IDs are never released. Store the returned ID and skip subscribe if one already exists. Call sforce.one.unsubscribe(subscriptionId) and reset the variable to null when the page no longer needs messages.