❄️ Winter Sale: 40% OFF AIWU
WINTER_SECRET
Valid until Mar 1st
JavaScript API: Embed AI Chat Anywhere on Your Page - AIWU – AI Plugin for WordPress
Table of Contents
< All Topics

JavaScript API: Embed AI Chat Anywhere on Your Page

After reading this guide, you’ll be able to embed a custom AI chat interface anywhere on your WordPress site — in a modal, sidebar, or inline in a page — using JavaScript without relying on AIWU’s default chat widget.

In this article: Initialize the SDK · Basic Chat Interface · Streaming Responses · Advanced Config · Common Issues

💡 For developers. This guide assumes JavaScript proficiency. If you don’t write code, use the built-in no-code chatbot builder instead.

Before You Start

You’ll need:

  • AIWU plugin v4.9+ installed
  • AIWU Developer API key (get your key)
  • A chatbot configured in AIWU (to get its ID)
  • Basic JavaScript knowledge

Step 1: Include the AIWU JavaScript SDK

Add this to your page’s <head> or before your closing </body> tag:

<script src="https://yoursite.com/wp-content/plugins/aiwu/assets/js/aiwu-chat-sdk.min.js"></script>

Or enqueue it in WordPress via your theme’s functions.php:

wp_enqueue_script(
    'aiwu-chat-sdk',
    plugins_url('aiwu/assets/js/aiwu-chat-sdk.min.js'),
    [],
    AIWU_VERSION,
    true
);

Step 2: Initialize a Basic Chat Session

const chat = new AIWUChat({
    apiKey: 'aiwu_live_xxxxxxxxxxxxxxxxxxxx',
    chatbotId: 1,
    sessionId: 'user-' + Math.random().toString(36).substr(2, 9),
    endpoint: 'https://yoursite.com/wp-json/aiwu/v1/chat'
});

// Send a message
async function sendMessage(userMessage) {
    const response = await chat.send(userMessage);
    console.log('AI response:', response.data.message);
    return response.data.message;
}

// Example usage
sendMessage("What are your business hours?").then(reply => {
    document.getElementById('chat-response').textContent = reply;
});

Step 3: Implement Streaming (Recommended)

Streaming makes responses appear word-by-word — much better UX than waiting for the full response.

const chat = new AIWUChat({
    apiKey: 'aiwu_live_xxxxxxxxxxxxxxxxxxxx',
    chatbotId: 1,
    sessionId: 'session-' + Date.now(),
    endpoint: 'https://yoursite.com/wp-json/aiwu/v1/chat',
    stream: true
});

async function sendWithStreaming(userMessage, outputElement) {
    outputElement.textContent = '';

    await chat.sendStream(userMessage, {
        onChunk: (chunk) => {
            outputElement.textContent += chunk;
        },
        onComplete: (fullResponse) => {
            console.log('Full response:', fullResponse);
        },
        onError: (error) => {
            outputElement.textContent = 'Error: ' + error.message;
        }
    });
}

Advanced Configuration Options

Option Type Default Description
apiKey string required Your AIWU developer API key
chatbotId integer required ID of the chatbot to use
sessionId string required Unique conversation thread ID
stream boolean false Enable streaming responses
context string null Additional context injected per message (e.g., current page URL)
language string 'en' Response language hint
timeout integer 30000 Request timeout in milliseconds

Injecting Dynamic Context

Pass page-specific context with each message so the AI can give more relevant answers:

// Inject current page context
const chat = new AIWUChat({
    apiKey: 'aiwu_live_xxxxxxxxxxxxxxxxxxxx',
    chatbotId: 1,
    sessionId: 'user-session-id',
    context: `
        Current page: ${window.location.pathname}
        Product: ${document.querySelector('.product-title')?.textContent}
        Category: ${document.querySelector('.product-category')?.textContent}
    `
});

Accessing Conversation History

// Get history for current session
const history = await chat.getHistory();
console.log(history.messages); // Array of {role, content, timestamp}

Complete Chat Widget Example

A minimal but functional chat widget you can drop into any page:

<!-- HTML -->
<div id="my-chat-widget" style="max-width: 400px; border: 1px solid #ddd; border-radius: 8px; padding: 16px;">
    <div id="messages" style="height: 300px; overflow-y: auto; margin-bottom: 12px;"></div>
    <input id="input" type="text" placeholder="Type a message..." style="width: 80%;">
    <button onclick="send()">Send</button>
</div>

<script>
const chat = new AIWUChat({
    apiKey: 'aiwu_live_xxxxxxxxxxxxxxxxxxxx',
    chatbotId: 1,
    sessionId: 'session-' + Date.now(),
    stream: true
});

const messages = document.getElementById('messages');
const input = document.getElementById('input');

async function send() {
    const text = input.value.trim();
    if (!text) return;
    input.value = '';

    // Show user message
    messages.innerHTML += `<p><strong>You:</strong> ${text}</p>`;

    // Show AI response (streaming)
    const aiMsg = document.createElement('p');
    aiMsg.innerHTML = '<strong>AI:</strong> ';
    const span = document.createElement('span');
    aiMsg.appendChild(span);
    messages.appendChild(aiMsg);

    await chat.sendStream(text, {
        onChunk: (chunk) => { span.textContent += chunk; },
        onComplete: () => { messages.scrollTop = messages.scrollHeight; }
    });
}

input.addEventListener('keydown', (e) => { if (e.key === 'Enter') send(); });
</script>

Common Issues

Problem: CORS error when making API calls.
Fix: AIWU API requires requests to come from allowed origins. Go to AIWU → Settings → API → Allowed Origins and add your domain. For local development, add http://localhost:3000.

Problem: SDK not loaded — “AIWUChat is not defined”.
Fix: Make sure the SDK script loads before your code. Add the SDK script tag before your chat code, or ensure WordPress enqueues it correctly.

Problem: Streaming not working — getting full response at once.
Fix: Make sure stream: true is set in AIWUChat config AND your server supports SSE (Server-Sent Events). Some caching plugins buffer responses — disable caching for the API endpoint path.

Still stuck? See the AIWU Developer API Reference or REST API Quick Start.

What’s Next

Last verified: AIWU v.4.9.2 · Updated: 2026-02-25

Scroll to Top