0

I have tried lightning-emp-api but it only works if the component is in the salesforce lightning pages itself, and not in my "homemade" experience sites.

Is there any way I can subscribe to such event on experience sites?

1 Answer 1

0

Community users don't have access to Push Topics and Platform Event, Data Change Event are built on Push Topics.

There is a way to do it -

you need to download cometd from cometD Extract and upload the cometd.js from the common folder as a static resource.

import { loadScript } from "lightning/platformResourceLoader";
import cometdlwc from "@salesforce/resourceUrl/cometd";
/*  connectedCallBack should be connectedCallback with a lower case b as JavaScript is case sensitive */

connectedCallback(){
loadScript(this, cometdlwc)
    .then(() => {
        var cometdlib = new window.org.cometd.CometD();
        
//Calling configure method of cometD class, to setup authentication which will be used in handshaking
  cometdlib.configure({
    url: window.location.protocol + '//' + window.location.hostname + '/cometd/47.0/',
    requestHeaders: { Authorization: 'OAuth ' + this.sessionId}, // you need get the sessionId from Apex
    appendMessageTypeToURL : false,
    logLevel: 'debug'
});

cometdlib.websocketEnabled = false;

cometdlib.handshake(function(status) {
            
    if (status.successful) {
        // Successfully connected to the server.
        // Now it is possible to subscribe or send messages
        console.log('Successfully connected to server');
        cometdlib.subscribe('/event/PlatformEvent__e', function (message) {
                  console.log('subscribed to message!'+ message);
       });
    } else {
        /// Cannot handshake with the server, alert user.
        console.error('Error in handshaking: ' + JSON.stringify(status));
     }
   });
  }
    });
}
1
  • Please edit the answer to warn about CometD constraints; Salesforce limits the number of concurrent CometD subscribers and event deliveries per day as per the documentation.
    – Phil W
    Commented Jan 17, 2023 at 14:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .