Start Chat on click of a Button from Salesforce Experience Cloud Site

Start Chat on click of a Button from Salesforce Experience Cloud Site

To initiate Chat on click of a Button from Salesforce Experience Cloud Site, we can make use of Lightning Web Component, Channel Menu and embedded_svc.liveAgentAPI.startChat().

Sample Lightning Web Component:

HTML:

<template>
    <lightning-card>
        <lightning-input 
            label="First Name"
            onchange={handleChange}
            class="slds-var-p-around_medium">
        </lightning-input>
        <lightning-input 
            label="Last Name"
            onchange={handleChange}
            class="slds-var-p-around_medium">
        </lightning-input>
        <lightning-input 
            label="Email"
            onchange={handleChange}
            class="slds-var-p-around_medium">
        </lightning-input>
        <lightning-input 
            label="Subject"
            onchange={handleChange}
            class="slds-var-p-around_medium">
        </lightning-input>
        <div slot="footer">
            <lightning-button
                label="Start Chat"
                variant="brand"  
                onclick={startChat}
                class="slds-var-p-around_medium">
            </lightning-button>
        </div>
    </lightning-card>
</template>

JavaScript:

import { LightningElement } from 'lwc';

export default class ChatComponent extends LightningElement {

    strFirstName;
    strLastName;
    strEmail;
    strSubject;

    handleChange( event ) {

        const strLabel = event.target.label;

        console.log( 
            'Label is', 
            strLabel
        );

        if ( strLabel == "First Name" ) {

            this.strFirstName = event.detail.value;

        } else if ( strLabel == "Last Name" ) {

            this.strLastName = event.detail.value;

        } else if ( strLabel == "Email" ) {

            this.strEmail = event.detail.value;

        } else if ( strLabel == "Subject" ) {

            this.strSubject = event.detail.value;

        } 

    }

    startChat() {

        console.log( 'Inside Start Chat' );
        embedded_svc.liveAgentAPI.startChat( {
            directToAgentRouting: {
                buttonId: "5735Y0000004xZG",
                fallback: true
            },
            prepopulatedPrechatFields: {
                FirstName: this.strFirstName,
                LastName: this.strLastName,
                Email: this.strEmail,
                Subject: this.strSubject
            }
        } );
        console.log( 'End of Start Chat' );

    }

}

js-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>57.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightningCommunity__Page</target>
    </targets>
</LightningComponentBundle>

Experience Cloud Site Builder Configuration:

Output:

Leave a Reply