Reset Chat when Agent ends Salesforce Enhanced Chat Session

Reset Chat when Agent ends Salesforce Enhanced Chat Session

How to Reset the Chat When an Agent Ends a Salesforce Enhanced Chat Session?

With the transition from legacy Live Agent to Salesforce Enhanced Chat (also known as Messaging for In-App and Web, or MIAW), developers and architects have access to a much more robust, asynchronous messaging framework. However, this asynchronous nature introduces new UX challenges that require custom JavaScript handling to ensure a smooth customer journey.

One of the most common challenges is managing the session state when a support agent formally closes the conversation.

The Problem: The Asynchronous Disconnect

In Salesforce Enhanced Chat, messaging sessions are designed to be persistent. When an agent ends the conversation in the Service Console, the Messaging Session is immediately closed on the agent’s side, and the Omni-Channel capacity is freed up.

However, on the user side, the chat widget remains active. Because the channel is asynchronous, the customer can still type a message into the existing chat window. If they do, the system treats it as a continuation, instantly re-initiating the Omni-Channel routing process and putting the user back into the queue—often without them realizing a new session has started.

For a cleaner user experience, you often want to forcefully reset or clear the chat session on the client side the moment the agent terminates it.

The Solution: Event Listeners and the User Verification API

To solve this, we can listen for specific state changes in the embedded messaging component and trigger a session wipe.

Here is the technical workflow:

  1. Listen for the status update: Use the onEmbeddedMessagingSessionStatusUpdate event listener to monitor the chat’s lifecycle.
  2. Evaluate the payload: Extract the event payload to verify that the session was ended specifically by the Agent (and not due to a network timeout or user action).
  3. Clear the session: Invoke the embeddedservice_bootstrap.userVerificationAPI.clearSession() method to clear the user’s persistent session data from the browser.

The Code Implementation

Below is the JavaScript snippet to achieve this. You can add this directly to the webpage hosting your Salesforce Embedded Messaging component.

JavaScript

window.addEventListener("onEmbeddedMessagingSessionStatusUpdate", (event) => {
                    console.log("START:: Status Update");
                
                    const tempContent = event.detail;
                    console.log(JSON.stringify(tempContent));
                    const sessionData = JSON.parse(tempContent.conversationEntry.entryPayload);

                    if (
                        sessionData.sessionStatus === "Ended" &&
                        sessionData.sessionStatusPrev === "Active" && 
                        sessionData.sessionEndedByRole === 'Agent' 
                    ) {
                        console.log("Active Session ended");
                        embeddedservice_bootstrap.userVerificationAPI
                        .clearSession()
                        .then(() => {
                            console.log("Session cleared successfully.");
                        })
                        .catch((error) => {
                            console.error("Error clearing session:", error);
                        })
                        .finally(() => {
                            console.log("clearSession finally.");
                            window.alert("Agent Ended the Chat!!!");
                        });
                    }
                    
                    console.log("END:: Status Update");
                });

How It Works

  • sessionStatus === "Ended" & sessionStatusPrev === "Active": This ensures we are only firing our logic during the exact transition from an active conversation to a closed one.
  • sessionEndedByRole === 'Agent': This guarantees we don’t accidentally clear the user’s session if they navigate away or experience a temporary connection drop; it only triggers when the Salesforce agent clicks “End Chat”.

Best Practices & Recommendations

While the code above functions perfectly to capture the event and clear the session, here are a few best practices and architectural recommendations to consider before pushing this to a production environment:

  • Replace window.alert with a Custom UI Prompt: The window.alert() method is synchronous, blocks the main thread, and generally provides a poor user experience. It is highly recommended to replace the alert in the .finally() block with a custom UI modal, a Toast notification, or an inline message within the DOM to gracefully inform the customer that the chat has concluded.
  • Sanitize console.log in Production: The snippet contains heavy console logging (console.log(JSON.stringify(tempContent))). While excellent for debugging in your Sandbox, these should be removed or wrapped in a debug-flag condition before deploying to production to avoid exposing session data structures to the browser console.
  • Handle the Widget State Post-Clear: After clearSession() executes, the user will be treated as a brand-new visitor if they open the chat again. Consider whether you want to automatically close the chat widget using DOM manipulation or hide the chat button entirely if you don’t want them immediately starting a new session.
  • Error Handling: The .catch() block correctly logs the error, but as a best practice, consider adding retry logic or a fallback UI notification so the user isn’t stuck in a “ghost” session if the clearSession() API fails due to network issues.

Reference Articles

https://developer.salesforce.com/docs/service/messaging-web/guide/event-listeners.html

https://developer.salesforce.com/docs/service/messaging-web/references/m4w-reference/userVerificationAPI.html

Leave a Reply