Skip to main content

Vanilla JavaScript Integration

This guide covers integrating Diosc without any framework - pure HTML, CSS, and JavaScript.

Quick Start

CDN (Simplest)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My App with AI</title>

<!-- Load Diosc -->
<script type="module" src="https://unpkg.com/@diosc-ai/assistant-kit@latest/dist/assistant-kit/assistant-kit.esm.js"></script>
</head>
<body>
<h1>My Application</h1>

<!-- AI Chat Component -->
<diosc-chat
backend-url="https://your-hub.example.com"
api-key="your-api-key">
</diosc-chat>

<script>
// Push auth to connect
diosc('auth', {
headers: { 'Authorization': 'Bearer ' + getToken() },
userId: getUserId()
});

function getToken() {
return localStorage.getItem('access_token') || 'demo-token';
}

function getUserId() {
return 'user-123';
}
</script>
</body>
</html>

NPM with Bundler

If using a bundler like Webpack, Rollup, or Parcel:

npm install @diosc-ai/client
import { loadDiosc } from '@diosc-ai/client';

const diosc = await loadDiosc({
backendUrl: 'https://your-hub.example.com',
apiKey: 'your-api-key'
});

diosc('auth', {
headers: { Authorization: `Bearer ${token}` },
userId: 'user-123'
});

Configuration

Basic Configuration

diosc('config', {
// Required
backendUrl: 'https://your-hub.example.com',
apiKey: 'your-api-key',

// Optional
verbose: false, // Debug logging (default: false)
reconnectAttempts: 5, // Number of reconnect attempts (default: 5)
reconnectDelay: 1000, // Delay between reconnect attempts in ms (default: 1000)
reconnectDelayMax: 5000, // Max delay between reconnects in ms (default: 5000)
connectionTimeout: 20000 // Connection timeout in ms (default: 20000)
});

Authentication

Push auth context directly. The engine handles the connection lifecycle:

// Login — push auth to connect
diosc('auth', {
headers: { 'Authorization': 'Bearer ' + token },
userId: parseJwt(token).sub,
tenantId: 'acme-corp'
});

// Logout — push null to disconnect
diosc('auth', null);

// Token refresh — push updated context (same userId = refresh, not re-login)
diosc('auth', {
headers: { 'Authorization': 'Bearer ' + newToken },
userId: parseJwt(newToken).sub // Same user
});

function parseJwt(token) {
const base64 = token.split('.')[1];
return JSON.parse(atob(base64));
}

Event Handling

Listening to Events

// Connection events
diosc('on', 'authenticated', () => {
console.log('Connected to Diosc Hub');
document.getElementById('status').textContent = 'Connected';
});

diosc('on', 'disconnected', () => {
console.log('Disconnected');
document.getElementById('status').textContent = 'Disconnected';
});

diosc('on', 'reconnected', () => {
console.log('Reconnected');
});

// Streaming events
diosc('on', 'stream:start', () => {
console.log('AI is responding...');
});

diosc('on', 'stream:chunk', ({ content }) => {
// Append streaming content to UI
appendToLastMessage(content);
});

diosc('on', 'stream:end', () => {
console.log('Response complete');
finalizeLastMessage();
});

// Tool events
diosc('on', 'tool:started', ({ toolName }) => {
console.log(`Executing: ${toolName}`);
showToolIndicator(toolName);
});

diosc('on', 'tool:completed', ({ toolName, durationMs }) => {
console.log(`${toolName} completed in ${durationMs}ms`);
hideToolIndicator();
});

// Error handling
diosc('on', 'session:error', ({ code, message, recoverable }) => {
console.error(`Error [${code}]:`, message);
if (!recoverable) showFatalError(message);
});

// Approval workflow
diosc('on', 'approval:request', ({ toolCalls }) => {
console.log('Approval needed for:', toolCalls.map(t => t.name));
// The <diosc-chat> component handles this automatically
});

Removing Listeners

// Store the unsubscribe function
const unsubscribe = diosc('on', 'stream:chunk', handleChunk);

// Later, remove the listener
unsubscribe();

Sending Messages

Programmatic Messages

// Send a message
diosc('invoke', 'Hello, AI!');

// Send with page context
diosc('invoke', 'Help me with this order', {
pageContext: {
path: '/orders/12345',
pageType: 'order-details'
}
});

Form Integration

<form id="chat-form">
<input type="text" id="message-input" placeholder="Type a message...">
<button type="submit">Send</button>
</form>

<script>
document.getElementById('chat-form').addEventListener('submit', (e) => {
e.preventDefault();
const input = document.getElementById('message-input');
const message = input.value.trim();

if (message) {
diosc('invoke', message);
input.value = '';
}
});
</script>

Page Context

Update context when the page changes using a navigation observer:

// Register a navigation observer
diosc('observe', 'navigation', (notify) => {
// Notify immediately with current path
notify({
path: window.location.pathname,
search: window.location.search,
hash: window.location.hash
});

// Listen for pushState/popstate changes
const originalPushState = history.pushState.bind(history);
history.pushState = function(...args) {
originalPushState(...args);
notify({
path: window.location.pathname,
search: window.location.search,
hash: window.location.hash
});
};

window.addEventListener('popstate', () => {
notify({
path: window.location.pathname,
search: window.location.search,
hash: window.location.hash
});
});
});

Session Management

// Start a new session
diosc('startNewSession');

// Load a previous session
diosc('loadSession', 'session-id-here');

// Search sessions
diosc('searchSessions', { query: 'billing issue', limit: 10 });

// Clear search
diosc('clearSessionSearch');

// Pin/unpin a session
diosc('pinSession', 'session-id', true);

// Rename a session
diosc('renameSession', 'session-id', 'Billing Discussion');

Custom Browser Tools

Register tools that the AI can invoke in the browser:

// Navigation tool
diosc('tool', 'navigate', ({ path }) => {
window.location.href = path;
return { navigated: true, path };
});

// Page info tool
diosc('tool', 'get_page_info', () => ({
title: document.title,
url: window.location.href,
selectedText: window.getSelection()?.toString() || ''
}));

// Show notification tool
diosc('tool', 'show_notification', ({ title, message }) => {
if (Notification.permission === 'granted') {
new Notification(title, { body: message });
}
return { shown: Notification.permission === 'granted' };
});

AI Intents

Use <ai-intent> to let the AI interact with your page:

<!-- Let AI fill a search box -->
<ai-intent name="search" description="Search for items" params="query">
<input id="search" type="text" data-param="query" placeholder="Search...">
<button data-action="submit">Search</button>
</ai-intent>

<!-- Let AI select a filter with confirmation -->
<ai-intent name="filter-category" description="Filter by category" params="category" confirm>
<select data-param="category">
<option value="all">All</option>
<option value="electronics">Electronics</option>
<option value="clothing">Clothing</option>
</select>
</ai-intent>

Styling

CSS Custom Properties

diosc-chat {
/* Colors */
--primary-color: #0066cc;
--background-color: #ffffff;
--text-color: #333333;

/* Typography */
--font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;

/* Layout */
--border-radius: 8px;
--chat-width: 380px;
--chat-max-height: 600px;
}

Dark Mode

@media (prefers-color-scheme: dark) {
diosc-chat {
--background-color: #1a1a1a;
--text-color: #ffffff;
}
}

/* Or with a class */
.dark-mode diosc-chat {
--background-color: #1a1a1a;
--text-color: #ffffff;
}

Positioning

/* The chat widget positions itself as a floating button + modal by default.
For full-page embed, override: */
diosc-chat.embedded {
position: relative;
width: 100%;
height: 100%;
--chat-width: 100%;
--chat-max-height: 100%;
}

Browser Compatibility

Diosc web components work in all modern browsers:

BrowserMinimum Version
Chrome67+
Firefox63+
Safari12+
Edge79+

For older browsers, you may need polyfills:

<script src="https://unpkg.com/@webcomponents/webcomponentsjs@2/webcomponents-loader.js"></script>

Troubleshooting

Component Not Rendering

Check if the script loaded:

if (typeof diosc === 'undefined') {
console.error('Diosc not loaded — check script tag');
}

Check browser console for errors.

CORS Errors

Your Diosc Hub needs to allow requests from your domain. Configure CORS in the assistant settings in the admin portal.

WebSocket Connection Failed

Check if WebSocket is supported and not blocked:

if (!window.WebSocket) {
console.error('WebSocket not supported');
}

Check firewall/proxy settings. Some corporate proxies block WebSocket connections.

Events Not Firing

Ensure you're subscribing before the event occurs:

// Subscribe first
diosc('on', 'authenticated', () => { /* ... */ });

// Then push auth (which triggers connect)
diosc('auth', { /* ... */ });

Next Steps