> ## Documentation Index
> Fetch the complete documentation index at: https://sitegpt.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# JavaScript SDK

> Embed your AI chatbot on any website

The SiteGPT JavaScript SDK allows you to embed your AI chatbot on any website with a simple script tag.

## Quick start

Add your chatbot to your website in under 60 seconds:

<Steps>
  <Step title="Get your chatbot ID">
    Find your chatbot ID in your dashboard under **Installation**.
  </Step>

  <Step title="Add the script">
    Copy and paste this code before the closing `</body>` tag:

    ```html theme={null}
    <script type="text/javascript">
    window.$sitegpt=[];
    (function(){
      d=document;
      s=d.createElement("script");
      s.src="https://sitegpt.ai/widget/YOUR_CHATBOT_ID.js";
      s.async=1;
      d.getElementsByTagName("head")[0].appendChild(s);
    })();
    </script>
    ```
  </Step>

  <Step title="Test">
    Reload your page and click the chat bubble to test your chatbot.
  </Step>
</Steps>

## Installation

The simplest way to add your chatbot:

```html theme={null}
<script type="text/javascript">
window.$sitegpt=[];
(function(){
  d=document;
  s=d.createElement("script");
  s.src="https://sitegpt.ai/widget/YOUR_CHATBOT_ID.js";
  s.async=1;
  d.getElementsByTagName("head")[0].appendChild(s);
})();
</script>
```

<Note>
  Replace `YOUR_CHATBOT_ID` with your actual chatbot ID from the Installation page.
</Note>

## Configuration via URL parameters

You can customize the chatbot behavior by adding URL parameters to the widget script:

* `hideBubble=true` - Hide the default chat bubble
* `open=true` - Open the chat widget automatically
* `mobile=false` - Hide the chat widget on mobile devices
* `delay=2000` - Delay widget initialization (in milliseconds)

**Example:**

```html theme={null}
<script type="text/javascript">
window.$sitegpt=[];
(function(){
  d=document;
  s=d.createElement("script");
  s.src="https://sitegpt.ai/widget/YOUR_CHATBOT_ID.js?hideBubble=true&open=true";
  s.async=1;
  d.getElementsByTagName("head")[0].appendChild(s);
})();
</script>
```

## SDK methods reference

Control your chatbot programmatically using the `$sitegpt` JavaScript SDK. All commands use the `push` method: `window.$sitegpt.push([command, ...args])`

<Note>
  For a complete interactive reference with copy-paste examples, visit the **SDK Methods** page in your chatbot dashboard under Installation.
</Note>

### Control widget visibility

#### Open the chat widget

Programmatically opens the chat widget window.

```javascript theme={null}
window.$sitegpt.push(['open']);
```

**Example: Open chat when user clicks a custom button**

```javascript theme={null}
document.getElementById('my-custom-chat-button').addEventListener('click', function() {
  window.$sitegpt.push(['open']);
});
```

#### Close the chat widget

Programmatically closes the chat widget window.

```javascript theme={null}
window.$sitegpt.push(['close']);
```

**Example: Close chat from another element**

```javascript theme={null}
document.getElementById('close-chat-link').addEventListener('click', function() {
  window.$sitegpt.push(['close']);
});
```

#### Toggle the chat widget

Opens the chat widget if it's closed, and closes it if it's open.

```javascript theme={null}
window.$sitegpt.push(['toggle']);
```

**Example: Use a single button to open or close the chat**

```javascript theme={null}
document.getElementById('toggle-chat-button').addEventListener('click', function() {
  window.$sitegpt.push(['toggle']);
});
```

#### Open with fresh conversation

Opens the chat widget and resets the conversation in a single flicker-free step. If there is an existing conversation, it will be cleared and a new one will be started.

```javascript theme={null}
window.$sitegpt.push(['open', { reset: true }]);
```

**Example: Always start a fresh conversation when user clicks your custom button**

```javascript theme={null}
document.getElementById('chat-button').addEventListener('click', function() {
  window.$sitegpt.push(['open', { reset: true }]);
});
```

<Tip>
  Use `['open', { reset: true }]` instead of calling `['open']` followed by `['do', 'conversation:reset']` separately. It avoids the visual flicker of the old conversation appearing briefly before the reset.
</Tip>

### Send messages programmatically

#### Send a message immediately

Sends a message to the chatbot immediately. The chat widget will open automatically if it's closed.

```javascript theme={null}
window.$sitegpt.push(['do', 'message:send', 'What are your pricing plans?']);
```

**Example: Send message when user clicks a pricing button**

```javascript theme={null}
document.getElementById('pricing-button').addEventListener('click', function() {
  window.$sitegpt.push(['do', 'message:send', 'What are your pricing plans?']);
});
```

**Example: Complete flow - open chat and send message**

```javascript theme={null}
window.$sitegpt.push(['open']);
setTimeout(() => {
  window.$sitegpt.push(['do', 'message:send', 'I need help with my account']);
}, 100);
```

#### Prefill the message input

Prefills the message input field with text. Users can edit the message before sending. The input field will be focused automatically.

```javascript theme={null}
window.$sitegpt.push(['set', 'message:text', "Hi! I'd like to get help with..."]);
```

**Example: Prefill input when user clicks a help button**

```javascript theme={null}
document.getElementById('help-button').addEventListener('click', function() {
  window.$sitegpt.push(['set', 'message:text', "Hi! I'd like to get help with..."]);
});
```

**Example: Open chat and prefill input**

```javascript theme={null}
window.$sitegpt.push(['open']);
setTimeout(() => {
  window.$sitegpt.push(['set', 'message:text', 'I have a question about billing']);
}, 100);
```

<Tip>
  Use `['do', 'message:send', ...]` when you want to send a message automatically without user interaction. Use `['set', 'message:text', ...]` when you want to suggest a message but let the user edit it before sending.
</Tip>

### Manage conversations

#### Reset the current conversation

Resets the current conversation thread and returns to the widget home page. This clears the conversation history and allows the user to start over.

```javascript theme={null}
window.$sitegpt.push(['do', 'conversation:reset']);
```

**Example: Add a "Start new conversation" button**

```javascript theme={null}
document.getElementById('new-conversation-button').addEventListener('click', function() {
  window.$sitegpt.push(['do', 'conversation:reset']);
});
```

**Example: Reset conversation after form submission**

```javascript theme={null}
document.getElementById('contact-form').addEventListener('submit', function(e) {
  e.preventDefault();
  // Handle form submission
  // Then reset the chat and return to home
  window.$sitegpt.push(['do', 'conversation:reset']);
});
```

<Note>
  This command is useful when you want to give users a clean slate, such as after completing a transaction, switching topics, or when they explicitly request to start over. The user will be returned to the widget home page where they can see their conversation history.
</Note>

<Tip>
  If you want to reset and open the chat in a single flicker-free step, use `window.$sitegpt.push(['open', { reset: true }])` instead. See [Open with fresh conversation](#open-with-fresh-conversation).
</Tip>

### Enhance chatbot context

#### Give extra context

Provide additional information to your SiteGPT bot for more relevant and contextual conversations, such as the current page the user is on.

```javascript theme={null}
window.$sitegpt.push(['set', 'context', [
  'You are an experienced sales executive. You need to guide the user to book a demo call.',
  'Current Page: Pricing Page \n Current Page URL: https://sitegpt.ai/pricing'
]]);
```

**Example: Provide page-specific context**

```javascript theme={null}
window.$sitegpt.push(['set', 'context', [
  'You are helping a premium customer.',
  'Current page: ' + document.title
]]);
```

### Manage user sessions

#### Automatically log the user in

Automatically log users into the chatbot without requiring email verification. This requires generating a secure signature on your backend.

```javascript theme={null}
window.$sitegpt.push(['set', 'user:email', [
  'user@example.com',
  'cd7cc422ea97c82d844b2373fdcd6259c9ee6e135af65ab6fe6ca85e3f07abb1'
]]);
```

<Warning>
  Never generate signatures in your frontend. Always generate signatures on your backend to keep your API key secure.
</Warning>

#### Generating signatures (Node.js backend example)

```javascript theme={null}
const crypto = require('crypto');

// Your API key from sitegpt.ai/billing (keep it private!)
const apiKey = '6338d1ac-9afc-4a7c-8812-ba9e3f8c48eb';

// Sign an email using HMAC-SHA256
function signEmail(email) {
  return crypto.createHmac('sha256', apiKey).update(email).digest('hex');
}

// Generate signature for your user
const signature = signEmail('user@example.com');
console.log('Signature:', signature);
```

**Security notes:**

* Use HMAC-SHA256 algorithm only
* Generate signatures on your backend server
* Never expose your API key in frontend code
* Each signature is unique to the email and your API key

#### Security of user verification

User verification uses the `HMAC-SHA256` signature algorithm, a standard and secure method for authenticating data.

When setting a user email via the `$sitegpt` object, you must provide the signature computed on your backend. This signature uses your secret API key, known only to you and SiteGPT. Because only you and SiteGPT can generate valid signatures for a given email, an attacker without your API key cannot impersonate users.

<Warning>
  **Never generate signatures directly in your front-end code.** Doing so would expose your API key in the browser, allowing anyone to impersonate your users. **Always generate signatures on your backend server and never leak your API key.**
</Warning>

### Customize widget appearance

#### Add custom CSS

Apply your own CSS to the chatbot widget and style it according to your branding.

```javascript theme={null}
window.$sitegpt.push(['set', 'css', ':root { --chat-color: green; }']);
```

**Example: Changing the font family**

```javascript theme={null}
window.$sitegpt.push(['set', 'css', 'body { font-family: "Your Custom Font", sans-serif; }']);
```

## Common use cases

### Custom chat trigger

Hide the default bubble and use your own button:

```html theme={null}
<button id="chat-button">Chat with us</button>

<script type="text/javascript">
  window.$sitegpt=[];
  (function(){
    d=document;
    s=d.createElement("script");
    s.src="https://sitegpt.ai/widget/YOUR_CHATBOT_ID.js?hideBubble=true";
    s.async=1;
    d.getElementsByTagName("head")[0].appendChild(s);
  })();
  
  document.getElementById('chat-button').addEventListener('click', function() {
    window.$sitegpt.push(['open']);
  });
</script>
```

### Context-aware chatbot

Provide page-specific context:

```html theme={null}
<script type="text/javascript">
  window.$sitegpt=[];
  (function(){
    d=document;
    s=d.createElement("script");
    s.src="https://sitegpt.ai/widget/YOUR_CHATBOT_ID.js";
    s.async=1;
    d.getElementsByTagName("head")[0].appendChild(s);
  })();
  
  // Set context after page loads
  window.addEventListener('load', function() {
    window.$sitegpt.push(['set', 'context', [
      'You are helping with ' + document.title,
      'Current URL: ' + window.location.href
    ]]);
  });
</script>
```

### Pre-filled messages

Suggest messages based on user actions:

```html theme={null}
<button id="pricing-question">Ask about pricing</button>

<script>
  document.getElementById('pricing-question').addEventListener('click', function() {
    window.$sitegpt.push(['open']);
    setTimeout(function() {
      window.$sitegpt.push(['set', 'message:text', 'What are your pricing plans?']);
    }, 100);
  });
</script>
```

### Authenticated users

Auto-login authenticated users by fetching signature from your backend:

```html theme={null}
<script type="text/javascript">
  window.$sitegpt=[];
  (function(){
    d=document;
    s=d.createElement("script");
    s.src="https://sitegpt.ai/widget/YOUR_CHATBOT_ID.js";
    s.async=1;
    d.getElementsByTagName("head")[0].appendChild(s);
  })();
  
  // Fetch user email and signature from your backend API
  fetch('/api/chatbot-auth')
    .then(res => res.json())
    .then(data => {
      window.$sitegpt.push(['set', 'user:email', [
        data.email,
        data.signature
      ]]);
    });
</script>
```

**Backend API example (Node.js):**

```javascript theme={null}
// /api/chatbot-auth endpoint
const crypto = require('crypto');

app.get('/api/chatbot-auth', (req, res) => {
  // Get the logged-in user's email from your session/auth system
  const userEmail = req.user.email;
  
  // Your SiteGPT API key (keep it secret!)
  const apiKey = process.env.SITEGPT_API_KEY;
  
  // Generate signature
  const signature = crypto
    .createHmac('sha256', apiKey)
    .update(userEmail)
    .digest('hex');
  
  res.json({
    email: userEmail,
    signature: signature
  });
});
```

## Styling

### Custom CSS

Apply custom styles to the chat widget:

```javascript theme={null}
window.$sitegpt.push(['set', 'css', `
  :root {
    --chat-color: #155DEE;
    --chat-text-color: #FFFFFF;
    --chat-font-size: 16px;
  }
`]);
```

### Available CSS variables

The widget supports these CSS variables:

* `--chat-color` - Primary brand color (used for bubble, buttons, etc.)
* `--chat-text-color` - Text color for elements using the brand color
* `--chat-font-size` - Base font size for the chat interface

<Note>
  The widget uses Tailwind CSS internally. You can target specific elements with custom CSS, but the available CSS variables are limited to those listed above.
</Note>

## Best practices

### Load asynchronously

The recommended installation method already loads the SDK asynchronously to avoid blocking page rendering:

```html theme={null}
<script type="text/javascript">
window.$sitegpt=[];
(function(){
  d=document;
  s=d.createElement("script");
  s.src="https://sitegpt.ai/widget/YOUR_CHATBOT_ID.js";
  s.async=1;
  d.getElementsByTagName("head")[0].appendChild(s);
})();
</script>
```

### Handle loading state

Check if the SDK is loaded before calling methods:

```javascript theme={null}
function callSiteGPT(command) {
  if (window.$sitegpt && window.$sitegpt.push) {
    window.$sitegpt.push(command);
  } else {
    // SDK not loaded yet, queue the command
    window.$sitegpt = window.$sitegpt || [];
    window.$sitegpt.push(command);
  }
}
```

### Provide context

Give your chatbot context about the current page:

```javascript theme={null}
window.$sitegpt.push(['set', 'context', [
  '',
  `Page: ${document.title}\nURL: ${window.location.href}`
]]);
```

### Test thoroughly

Test your integration across:

* Different browsers (Chrome, Firefox, Safari, Edge)
* Mobile devices (iOS, Android)
* Different screen sizes
* With ad blockers enabled

## Troubleshooting

<AccordionGroup>
  <Accordion title="Chatbot not appearing" icon="eye-slash">
    <Info>If your chatbot doesn't appear, try these solutions:</Info>

    **Check the script tag**\
    Ensure the script is added before `</body>` and the chatbot ID is correct.

    **Check browser console**\
    Look for JavaScript errors that might prevent loading.

    **Verify chatbot is published**\
    Ensure your chatbot is published in the dashboard.

    **Test in incognito mode**\
    Rule out browser extensions or cached files.
  </Accordion>

  <Accordion title="Methods not working" icon="code">
    <Info>If SDK methods aren't working, verify these items:</Info>

    **Wait for SDK to load**\
    Ensure the SDK is fully loaded before calling methods.

    **Check syntax**\
    Verify you're using the correct method syntax.

    **Review console errors**\
    Check for JavaScript errors in the browser console.
  </Accordion>

  <Accordion title="Styling issues" icon="palette">
    <Info>If custom styles aren't applying, try these fixes:</Info>

    **Check CSS specificity**\
    Your styles may need `!important` to override defaults.

    **Verify CSS syntax**\
    Ensure your CSS is valid.

    **Clear cache**\
    Clear browser cache and reload the page.
  </Accordion>
</AccordionGroup>

## Next steps

<CardGroup cols={2}>
  <Card title="Installation guide" icon="download" href="/setup/integrating-with-your-website">
    Detailed installation instructions
  </Card>

  <Card title="Tracking events" icon="chart-mixed" href="/developers/tracking-events">
    Track chatbot activity in GTM, GA4, or custom analytics
  </Card>

  <Card title="Webhooks" icon="webhook" href="/developers/webhooks">
    Set up webhooks for real-time events
  </Card>

  <Card title="Appearance" icon="palette" href="/features/appearance">
    Customize chatbot appearance
  </Card>

  <Card title="API reference" icon="brackets-curly" href="/api-reference/v2/getting-started">
    Explore the REST API
  </Card>
</CardGroup>
