Auto-Start Salesforce Enhanced Chat with Custom or Static Messages

Auto-Start Salesforce Enhanced Chat with Custom or Static Messages

🤖 Auto-Start Salesforce Enhanced Chat with Custom or Static Messages (A Step-by-Step Guide)

Tired of making your customers manually type the same message every time they start a chat? Salesforce Enhanced Chat (also known as Embedded Messaging) offers powerful JavaScript utility APIs to automate this process. By programmatically launching the chat and sending a predefined or custom message, you can significantly enhance the user experience, speed up support, and even trigger specific routing rules or Omni-Channel flows in Salesforce.

This guide walks you through the essential steps and JavaScript methods to implement this functionality.


🔑 Key JavaScript APIs for Enhanced Chat Control

To achieve this customized chat experience, we utilize three critical functions from the Salesforce Embedded Messaging SDK (embeddedservice_bootstrap):

API FunctionPurpose
embeddedservice_bootstrap.settings.hideChatButtonOnLoad = true;Hides the default chat button when the page loads, allowing you to use your own custom launch buttons or inputs.
embeddedservice_bootstrap.utilAPI.launchChat();Programmatically opens the chat window. This is called when the user interacts with your custom button or input field.
embeddedservice_bootstrap.utilAPI.sendTextMessage(message);Sends a specific message into the active chat session. This is what we use to send the custom or static initial text.

🛠️ Implementation: Custom Input and Static Buttons

The following code snippet demonstrates how to launch the chat and send a message based on two common scenarios:

  1. Custom Message: The user types a message into a standard HTML input field.
  2. Static Message: The user clicks a predefined button (e.g., “Need help with my Order”).

Complete HTML and JavaScript Code Snippet

HTML

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Chat Input Example</title>

  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f7f8fa;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      margin: 0;
    }

    .chat-container {
      background: #fff;
      border: 1px solid #ddd;
      border-radius: 10px;
      width: 400px;
      padding: 16px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      display: flex;
      flex-direction: column;
    }

    .chat-input-area {
      display: flex;
      border: 1px solid #ccc;
      border-radius: 20px;
      padding: 8px 12px;
      background: #f1f1f1;
    }

    .chat-input {
      flex: 1;
      border: none;
      background: transparent;
      outline: none;
      font-size: 16px;
      padding: 6px;
    }

    .send-button {
      background-color: #0078ff;
      border: none;
      color: white;
      border-radius: 50%;
      width: 36px;
      height: 36px;
      cursor: pointer;
      font-size: 16px;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: background 0.2s;
    }

    .send-button:hover {
      background-color: #005fd1;
    }

    /* --- CSS for Styling the Button --- */
    .send-message-button {
      /* Background and Dimensions */
      background-color: #00008b; /* A deep blue, similar to the image */
      color: white; /* White text */
      padding: 15px 30px; /* Padding for height and width */
      font-size: 18px; /* Readable text size */
      font-weight: bold;
      cursor: pointer; /* Changes mouse to a pointer on hover */
      border: none; /* Remove default button border */
      display: inline-block; /* Allows setting padding/margin */
      text-align: center;
      border-radius: 5px; /* Slight rounding of corners */
  
      /* The White Border/Outline Effect */
      box-shadow: 0 0 0 2px white; /* A 2px white "stroke" */
      outline: 2px solid #00008b; /* Helps create the gap/depth effect */
    }
  
    .send-message-button:hover {
      background-color: #0000a0; /* Slightly lighter blue on hover */
    }
  </style>

  <script type="text/javascript">
    function initEmbeddedMessaging() {
      try {
        embeddedservice_bootstrap.settings.language = 'en_US'; // For example, enter 'en' or 'en-US'

        // Hiding Chat Button on page load
        embeddedservice_bootstrap.settings.hideChatButtonOnLoad = true;

        /* START:: Conversation Opened Listener */
        window.addEventListener("onEmbeddedMessagingConversationOpened", (event) => {
          hideChatContainer();
        });
        /* END:: Conversation Opened Listener */

        /* START:: Conversation Closed Listener */
        window.addEventListener("onEmbeddedMessagingWindowClosed", (event) => {
          showChatContainer();
        });
        /* END:: Conversation Closed Listener */

        /* START:: Button Created Listener */
        window.addEventListener("onEmbeddedMessagingButtonCreated", (event) => {
          showChatContainer();
        });
        /* END:: Button Created Listener */

        embeddedservice_bootstrap.init(
          '00DHo000002fRR9',
          'MIAW',
          'https://<Your URL>',
          {
            scrt2URL: 'https://<Your Domain>-scrt.com'
          }
        );
      } catch (err) {
        console.error('Error loading Embedded Messaging: ', err);
      }
    }
  </script>

  <script 
    type="text/javascript" 
    src="https://<Your URL>/assets/js/bootstrap.min.js" 
    onload="initEmbeddedMessaging()">
  </script>
</head>

<body>
  <div class="chat-container">
    <div>
      Welcome to our Chat!!!
      <br /><br /><br />
    </div>

    <div class="chat-input-area">
      <input 
        type="text" 
        id="chatInput" 
        class="chat-input" 
        placeholder="Type a message..." 
      />
      <button class="send-button" id="sendBtn">➤</button>
    </div>

    <div>
      <br/><br/>
      <button class="send-message-button" id="orderButton">
        Need help with my Order
      </button>
      <br/><br/>
      <button class="send-message-button" id="caseButton">
        Need help with my Case
      </button>
    </div>
  </div>

  <script>
    function showChatContainer() {
      const chatContainer = document.querySelector('.chat-container');
      chatContainer.style.display = 'block';
    }

    function hideChatContainer() {
      const chatContainer = document.querySelector('.chat-container');
      chatContainer.style.display = 'none';
    }

    function launchChat() {
      embeddedservice_bootstrap.utilAPI.launchChat()
          .then(() => {
            console.log('Successfully launched Messaging');
          })
          .catch(() => {
            console.log('Some error occurred when launching Messaging');
          })
          .finally(() => {
            console.log('Successfully launched Messaging - Finally');
          });
    }

    function sendMessageToChat(message) {
      setTimeout(() => {
          embeddedservice_bootstrap.utilAPI.sendTextMessage(message)
            .then(() => {
              console.log("Message sent");
            })
            .catch(() => {
              console.log("Message not sent");
            })
            .finally(() => {
              console.log("Message sent - finally");
            });
        }, 3000);
    }

    const sendBtn = document.getElementById('sendBtn');
    const chatInput = document.getElementById('chatInput');

    sendBtn.addEventListener('click', () => {
      const message = chatInput.value.trim();
      if (message) {
        console.log(message);
        chatInput.value = '';
        hideChatContainer();

        launchChat();

        sendMessageToChat(message);
      } else {
        alert("Please enter a message first!");
      }
    });

    // Allow pressing Enter to send the message
    chatInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        sendBtn.click();
      }
    });

    // Get the button element using its ID
    const orderButton = document.getElementById('orderButton');
    // Add an event listener that runs a function when the button is clicked
    orderButton.addEventListener('click', function() {
      // Get the text content of the button
      const orderButtonText = orderButton.textContent.trim();
      
      // Display the text in the browser's console
      console.log(orderButtonText);
      launchChat();
      sendMessageToChat(orderButtonText);
    });

    // Get the button element using its ID
    const caseButton = document.getElementById('caseButton');
    // Add an event listener that runs a function when the button is clicked
    caseButton.addEventListener('click', function() {
      // Get the text content of the button
      const caseButtonText = caseButton.textContent.trim();
      
      // Display the text in the browser's console
      console.log(caseButtonText);
      launchChat();
      sendMessageToChat(caseButtonText);
    });
  </script>
</body>
</html>

Code Explanation: The Workflow

The key to this implementation is the sequence of events tied to the user’s action:

  1. Hiding the Default Button: The line embeddedservice_bootstrap.settings.hideChatButtonOnLoad = true; in the initEmbeddedMessaging function ensures the default chat button is hidden, giving us full control over the user interface with the custom chat-container div.
  2. User Interaction: When a user clicks the Send button or one of the static message buttons (orderButton, caseButton), the associated JavaScript listener is triggered.
  3. Hiding Custom UI: The hideChatContainer() function is called to visually remove the custom input box, preparing for the Salesforce chat window to appear.
  4. Launching Chat: The launchChat() function, which calls embeddedservice_bootstrap.utilAPI.launchChat(), opens the Enhanced Chat window.
  5. Sending the Message: The sendMessageToChat(message) function calls embeddedservice_bootstrap.utilAPI.sendTextMessage(message). Crucially, this is wrapped in a setTimeout function with a 3-second delay. This delay is essential to ensure the chat session is fully opened and ready to receive the message before the API call is executed.

Leave a Reply