1. Webchat Embedding
  2. Webchat Headless Mode

Webchat Embedding

Webchat Headless Mode

Learn how to use webchat in headless mode to create custom chat interfaces.

Headless mode allows you to use the core webchat functionality with your own custom UI. This is useful when you want complete control over the appearance and behavior of the chat interface.

Note: This example demonstrates only text messaging functionality. Advanced features like file uploads and voice notes are not covered in this basic implementation.

Getting Started

To use webchat in headless mode, you need to include the webchat core script in your HTML:

html
        <script defer src="https://webchat.notifications.stubber.com/v2/client/core.js"></script>

      

This script makes the StubberWebchatCore object available globally, which provides all the necessary methods for connecting to and interacting with the webchat service.

Accessing the Webchat Core Object

After the script is loaded, you can access the webchat core object from the global window object:

js
        // Initialize reference to the webchat core
const webchat = window.StubberWebchatCore;

      

This is typically done inside the window.onload event handler to ensure the script has finished loading:

js
        window.onload = function() {
  // Initialize reference to the webchat core
  const webchat = window.StubberWebchatCore;
  
  // Now you can use webchat methods
  // ...
};

      

Configuration Options

When configuring the webchat connection, you need to provide several options:

js
        webchat.webchat_connection_config({
  // Profile UUID for identifying your chat interface
  profileuuid: "your-profile-uuid",
  
  // Optional: "live" or "draft", defaults to "live"
  branch: "live",
  
  // Required: callback for receiving messages
  payload_callback: (payloads) => {
    // Handling incoming messages
  }
});

      

Sending Messages

To send a text message:

js
        webchat.webchat_send_payload({
  webchat_message: {
    type: "text", 
    data: "Hello, world!"
  }
});

      

Receiving Messages

Messages are received through the payload_callback function provided during configuration. Each message has the following structure:

js
        {
  // Direction of the message: "IN" for incoming, "OUT" for outgoing
  payload_direction: "IN",
  
  // The actual message content
  webchat_message: {
    type: "text",
    data: "Hello! How can I help you today?"
  }
}

      

Complete Example

Here's a complete example with a simple UI for sending and receiving messages:

html
        <!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Webchat Headless Mode Simple Example</title>
  <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
  <script defer src="https://webchat.notifications.stubber.com/v2/client/core.js"></script>

  <style>
    /* Simple styling */
    .message-container {
      height: 300px;
      overflow-y: auto;
      border: 1px solid #e2e8f0;
      border-radius: 0.5rem;
      padding: 1rem;
      margin-bottom: 1rem;
    }
    
    .message-in {
      background-color: #e2e8f0;
      padding: 0.75rem;
      border-radius: 0.5rem;
      margin-bottom: 0.75rem;
      width: 70%;
    }
    
    .message-out {
      background-color: #3b82f6;
      color: white;
      padding: 0.75rem;
      border-radius: 0.5rem;
      margin-bottom: 0.75rem;
      margin-left: auto;
      width: 70%;
    }
    
    .input-container {
      display: flex;
      gap: 0.5rem;
    }
    
    .input-field {
      flex-grow: 1;
      padding: 0.75rem;
      border: 1px solid #e2e8f0;
      border-radius: 0.5rem;
    }
    
    .send-button {
      background-color: #3b82f6;
      color: white;
      padding: 0.75rem 1.5rem;
      border: none;
      border-radius: 0.5rem;
      cursor: pointer;
    }
    
    .send-button:hover {
      background-color: #2563eb;
    }
  </style>

  <script>
    let webchat;
    let messages = [];
    let messagesContainer;

    window.onload = function () {
      // Initialize references
      webchat = window.StubberWebchatCore;
      messagesContainer = document.getElementById('messagesContainer');

      // Get parameters from URL
      const searchParams = new URLSearchParams(window.location.search);
      const profile_uuid = searchParams.get("profile_uuid") || "";
      const branch = searchParams.get("branch") || "live";
      
      // Display configuration info
      document.getElementById('configInfo').innerHTML = `
        <strong>Configuration:</strong><br>
        Profile UUID: ${profile_uuid || "Not set"}<br>
        Branch: ${branch}
      `;

      // Configure the webchat connection
      webchat.webchat_connection_config({
        profileuuid: profile_uuid,
        branch: branch,
        payload_callback: (payloads) => {
          // Called when new messages arrive
          console.log("Received messages:", payloads);
          messages = payloads;
          renderMessages();
          
          // Scroll to bottom when new messages arrive
          setTimeout(() => {
            if (messagesContainer) {
              messagesContainer.scrollTop = messagesContainer.scrollHeight;
            }
          }, 100);
        }
      });

      // Connect to the webchat service
      webchat.webchat_connect();

      // Set up send button handler
      document.getElementById('sendButton').addEventListener('click', sendMessage);
      
      // Set up message input enter key handler
      document.getElementById('messageInput').addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
          e.preventDefault();
          sendMessage();
        }
      });
    };

    // Function to send a text message
    function sendMessage() {
      const messageInput = document.getElementById('messageInput');
      const message = messageInput.value.trim();
      
      if (!message) return; // Don't send empty messages
      
      // Send the message
      webchat.webchat_send_payload({
        webchat_message: {
          type: "text",
          data: message,
        }
      });

      // Clear the input field
      messageInput.value = "";
    }

    // Function to render messages
    function renderMessages() {
      let messagesHTML = '';

      messages.forEach(message => {
        if (message.payload_direction === "IN") {
          // Incoming message (from bot/agent)
          messagesHTML += `
            <div class="message-in">
              ${message.webchat_message.data || ''}
            </div>
          `;
        } else if (message.payload_direction === "OUT") {
          // Outgoing message (from user)
          messagesHTML += `
            <div class="message-out">
              ${message.webchat_message.data || ''}
            </div>
          `;
        }
      });

      messagesContainer.innerHTML = messagesHTML;
    }
  </script>
</head>

<body class="bg-gray-50">
  <div class="container mx-auto p-4 max-w-2xl">
    <h1 class="text-2xl font-bold mb-2">Webchat Headless Mode Example</h1>
    <p class="mb-4 text-gray-600">This is a simple example of using the webchat in headless mode.</p>
    
    <div id="configInfo" class="p-3 bg-blue-50 text-blue-800 rounded-lg mb-4 text-sm"></div>
    
    <div class="bg-white p-4 rounded-lg shadow-sm">
      <!-- Messages container -->
      <div id="messagesContainer" class="message-container">
        <!-- Messages will be rendered here -->
      </div>
      
      <!-- Message input and send button -->
      <div class="input-container">
        <input 
          id="messageInput" 
          class="input-field" 
          type="text" 
          placeholder="Type your message..."
        />
        <button id="sendButton" class="send-button">Send</button>
      </div>
    </div>
    
    <div class="mt-6 bg-yellow-50 p-4 rounded-lg text-sm">
      <h2 class="font-bold mb-2">How to use this example:</h2>
      <ol class="list-decimal pl-5 space-y-2">
        <li>Add <code class="bg-gray-100 px-1 rounded">?profile_uuid=YOUR_PROFILE_UUID</code> to the URL.</li>
        <li>Optionally add <code class="bg-gray-100 px-1 rounded">&branch=live|draft</code> to specify branch.</li>
        <li>Type a message and click Send or press Enter to send it.</li>
      </ol>
      
      <h2 class="font-bold mt-4 mb-2">Implementation:</h2>
      <p>This example demonstrates how to:</p>
      <ul class="list-disc pl-5 space-y-1">
        <li>Initialize the webchat in headless mode</li>
        <li>Configure the connection with profile UUID, branch, and session UUID</li>
        <li>Send and receive simple text messages</li>
        <li>Display messages in a simple UI</li>
      </ul>
    </div>
  </div>
</body>

</html>

      

API Reference

webchat_connection_config(config)

Configures the webchat connection.

js
        webchat.webchat_connection_config({
  profileuuid: String, // Profile UUID for identifying your chat interface
  branch: String,      // Optional: "live" or "draft"
  payload_callback: Function // Required: Callback for messages
});

      

webchat_connect()

Connects to the webchat service using the current configuration.

js
        webchat.webchat_connect();

      

webchat_send_payload(payload)

Sends a message to the webchat service.

js
        webchat.webchat_send_payload({
  webchat_message: {
    type: String,  // e.g., "text"
    data: String,  // The message content
  }
});