DocuChat Logo
Advanced Features

Context Injection

Learn how to use context injection to enhance your chatbot experience.

You can dynamically add user context to an embedded chat session using the window messaging API. This allows you to provide additional information that can enhance the chat experience.

Example Use Cases:
  • An e-commerce website could add user context about recent purchases, cart items, and browsing history to help the chatbot provide more personalized product recommendations and support
  • A SaaS platform could provide information about the user's subscription tier, enabled features, and recent usage patterns to help the chatbot give more relevant troubleshooting assistance

Usage

Send a message to the embedded chat iframe using postMessage:

// Get a reference to your chat iframe
const chatIframe = document.getElementById("your-chat-iframe-id");

// Send context to the chat
chatIframe.contentWindow.postMessage({
  type: "addUserContext",
  context: "Your context information here"
}, "*");

Best Practices

  • The context parameter must be a string and cannot be longer than 3000 characters, otherwise it will be truncated.
  • The context will be associated with the current chat session
  • Any previous context will be overwritten with the new context, INCLUDING auto-generated user information context, if enabled in the chatbot settings.
  • The message must be sent to the correct iframe origin
  • Make sure the iframe is fully loaded before sending messages to avoid errors. You can use the onload event handler if you need to add context on page load:
    chatIframe.onload = () => {
      // Send context after iframe is loaded
      chatIframe.contentWindow.postMessage({
        type: "addUserContext",
        context: "Your context information here"
      }, "*");
    };