# Widget

Put a contact form or a live chat on your site. Each message becomes a ticket, and the conversation continues by email. With the live chat, answerable's agent answers visitors from your help center's articles, and offers to send the chat to your team when it can't help. Admins set it up under **Help center → Widget**, where the preview shows it as visitors will see it and the script tag already has your choices.

## Adding the script

Add the script tag once to every page that should have the widget, usually in the root layout or base template, just before the closing `</body>` tag. Copy it from **Help center → Widget**; it looks like this, with your own key:

```html
<script src="https://staging.preview.answerable.co/widget.js" data-key="wgt_…" async></script>
```

It adds a round button in the bottom right corner of the page that opens the chat or the form, whichever the widget is set to open.

- Keep it a classic, async script tag with its `data-` attributes: the script reads its settings from its own tag (`document.currentScript`). If your framework has its own script component, like `next/script`, make sure the attributes reach the rendered tag. Don't bundle it or load it as a module.
- `data-key` is public, so it's fine in the page.
- If your site sets a Content Security Policy, allow `https://staging.preview.answerable.co` in `script-src` and `frame-src`.

### Options

The tag takes these attributes, each optional:

| Attribute | Does |
| --- | --- |
| `data-color="#4f46e5"` | The button's color. Dark grey by default. |
| `data-launcher="none"` | No button of ours: open the widget from your own links with the JavaScript below. `answerable.setLauncher(true)` can show ours later. |
| `data-position="bottom-left"` | Where our button sits: `bottom-right` (the default), `bottom-left`, or `top-right`. |
| `data-theme="dark"` | Start in `light` or `dark`. It follows the visitor's setting by default; `answerable.setTheme` changes it later. |
| `data-title="Report a bug"` | The contact form's heading. "Contact" and your workspace's name by default. |
| `data-placeholder="Ask about your plan"` | Grey text in the message box, the chat's or the form's, in place of the usual one. It's never sent, and it shows as written whatever language the widget speaks. |

### Sites

The widget only works on the sites listed under **Help center → Widget → Sites**, so nobody can put it on theirs. An entry like `https://*.example.com` covers each subdomain one level down over `https`, but not `example.com` itself. Anywhere else, local development included (like `http://localhost:3000`), it says "This form can't be used on this site" until that address is added.

## JavaScript

The script sets `window.answerable` when it loads, and fires `answerable:ready` on `window`.

```js
// Open the widget: the chat, or the form if that's what it opens
answerable.open();

// Open the contact form, even when the widget opens the chat
answerable.open({ form: true });

// Open the form with fields filled in; visitors can still change them
answerable.open({ name: "Pat Lee", email: "pat@example.com", message: "About invoice 1042: " });

// Open it with its own title this time, e.g. from a "Report a bug" link; the next open() without one has the usual title
answerable.open({ title: "Report a bug" });

// Open it with your own grey text in the message box this time; it's never sent (see "A placeholder or a message" below)
answerable.open({ placeholder: "Tell us about your team and what you need" });

answerable.close();

// Keep it in step with your site's own light or dark switch: "light", "dark", or null to follow the visitor's setting
answerable.setTheme("dark");

// Show or hide our button, whatever data-launcher was at first; an open widget stays open, and open() still works
answerable.setLauncher(false);

// Tell your team and answerable's agent about the visitor: kept with each message and chat from now on. null clears it
answerable.setContext({ plan: "Pro", projectId: "p_1042" });

// "open", "close", or "sent" (a message or chat reached your team). Returns a function that stops listening.
const stop = answerable.on("sent", () => console.log("Message sent"));
```

The script loads in the background, so code that runs early should check that `window.answerable` exists, or wait for `answerable:ready`. If your site has its own light or dark switch, call `answerable.setTheme` with the current choice once the widget is ready, and again whenever it changes.

### Context

Each message and chat already records the page it came from (without its query string) and the visitor's browser. If your site knows something that would help support answer, like the visitor's plan or what they have open, pass it with `answerable.setContext`, or as `window.answerableContext` before the script, and set it again when it changes. Up to 20 values by name, each text (200 characters at most), a number, or `true` or `false`. Never put secrets or tokens in it.

### A placeholder or a message

`message` puts text in the box that's sent as the visitor's own unless they change it, and many send it as it is. `placeholder` only suggests what to write, in grey, and is never sent. For a link about something specific, like a pricing page's "Talk to us about a custom plan", a placeholder keeps visitors from sending your words as theirs. Since it isn't sent, say what it's about in the context too, so it's on the ticket:

```js
// setContext replaces the whole context, so keep what you already pass, and set it back once it no longer applies
answerable.setContext({ ...context, inquiry: "Custom plan inquiry from the pricing page" });
answerable.open({ placeholder: "Tell us about your team and what you need" });
```

### TypeScript

```ts
type AnswerableIdentity = { email: string; name?: string | null; expires: number; signature: string };

declare global {
  interface Window {
    answerable?: {
      open(options?: { form?: boolean; name?: string; email?: string; message?: string; title?: string; placeholder?: string }): void;
      close(): void;
      setTheme(theme: "light" | "dark" | null): void;
      setLauncher(visible: boolean): void;
      setContext(context: Record<string, string | number | boolean> | null): void;
      identify(identity: AnswerableIdentity | null): void;
      on(event: "open" | "close" | "sent", callback: () => void): () => void;
    };
    answerableIdentity?: AnswerableIdentity;
    answerableContext?: Record<string, string | number | boolean>;
  }
}
```

## Signing in visitors

Without this, visitors confirm their address with a code emailed to them before their message is sent. If your site has accounts, people signed in to it can skip the code and have their name and address filled in, and the chat can answer questions about their own account when **Look up signed-in visitors' accounts** is on: your server signs their address with the widget's secret, and answerable checks the signature.

The secret is under **Help center → Widget → Signed-in visitors**. Keep it on your server, in an environment variable such as `ANSWERABLE_WIDGET_SECRET`, never in the page.

On the server, for the signed-in user:

- `expires`: a Unix time in seconds, at most 7 days ahead. Sign when the page renders; a day ahead is plenty.
- `signature`: HMAC-SHA256 of the text `<email>:<expires>`, keyed with the secret, in hex. Sign the email exactly as you send it.

Put the result on the page as `window.answerableIdentity`, before the widget's script, with `<` escaped so the data can't end the tag. In the common frameworks:

```tsx Next.js
// app/layout.tsx: sign the address of the person signed in to your site
import { createHmac } from "node:crypto";

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const user = await getCurrentUser(); // however your app reads its session
  let identity = null;
  if (user) {
    const expires = Math.floor(Date.now() / 1000) + 24 * 60 * 60; // up to 7 days ahead
    const signature = createHmac("sha256", process.env.ANSWERABLE_WIDGET_SECRET!)
      .update(user.email + ":" + expires)
      .digest("hex");
    identity = { email: user.email, name: user.name, expires, signature };
  }
  return (
    <html lang="en">
      <body>
        {children}
        {/* Before the widget's script */}
        {identity && (
          <script
            dangerouslySetInnerHTML={{
              __html: "window.answerableIdentity = " + JSON.stringify(identity).replace(/</g, "\\u003c"),
            }}
          />
        )}
      </body>
    </html>
  );
}
```

```js Express
// On your server: sign the address of the person signed in to your site
import { createHmac } from "node:crypto";

app.use((req, res, next) => {
  if (req.user) {
    const expires = Math.floor(Date.now() / 1000) + 24 * 60 * 60; // up to 7 days ahead
    const signature = createHmac("sha256", process.env.ANSWERABLE_WIDGET_SECRET)
      .update(req.user.email + ":" + expires)
      .digest("hex");
    res.locals.answerableIdentity = { email: req.user.email, name: req.user.name, expires, signature };
  }
  next();
});

<!-- In your layout (EJS here), before the widget's script -->
<% if (locals.answerableIdentity) { %>
  <script>window.answerableIdentity = <%- JSON.stringify(answerableIdentity).replace(/</g, "\\u003c") %>;</script>
<% } %>
```

```erb Rails
# app/helpers/application_helper.rb: sign the address of the person signed in
def answerable_identity
  expires = 24.hours.from_now.to_i # up to 7 days ahead
  secret = ENV.fetch("ANSWERABLE_WIDGET_SECRET")
  signature = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{current_user.email}:#{expires}")
  { email: current_user.email, name: current_user.name, expires: expires, signature: signature }
end

<%# app/views/layouts/application.html.erb, before the widget's script %>
<% if current_user %>
  <script>window.answerableIdentity = <%= answerable_identity.to_json.html_safe %>;</script>
<% end %>
```

```python Django
# context_processors.py, listed in TEMPLATES' context_processors: sign the signed-in person's address
import hashlib, hmac, os, time

def answerable_identity(request):
    if not request.user.is_authenticated:
        return {}
    email = request.user.email
    expires = int(time.time()) + 24 * 60 * 60  # up to 7 days ahead
    secret = os.environ["ANSWERABLE_WIDGET_SECRET"].encode()
    signature = hmac.new(secret, f"{email}:{expires}".encode(), hashlib.sha256).hexdigest()
    identity = {"email": email, "name": request.user.get_full_name(), "expires": expires, "signature": signature}
    return {"answerable_identity": identity}

{# In your base template, before the widget's script #}
{% if answerable_identity %}
  {{ answerable_identity|json_script:"answerable-identity" }}
  <script>window.answerableIdentity = JSON.parse(document.getElementById("answerable-identity").textContent);</script>
{% endif %}
```

```php Laravel
// app/Providers/AppServiceProvider.php, in boot(): sign the address of the person signed in
// (with use Illuminate\Support\Facades\View; at the top)
View::composer('layouts.app', function ($view) {
    $user = auth()->user();
    if (! $user) {
        return;
    }
    $expires = time() + 24 * 60 * 60; // up to 7 days ahead
    // config/services.php: 'answerable' => ['widget_secret' => env('ANSWERABLE_WIDGET_SECRET')]
    $secret = config('services.answerable.widget_secret');
    $view->with('answerableIdentity', [
        'email' => $user->email,
        'name' => $user->name,
        'expires' => $expires,
        'signature' => hash_hmac('sha256', $user->email . ':' . $expires, $secret),
    ]);
});

{{-- resources/views/layouts/app.blade.php, before the widget's script --}}
@isset($answerableIdentity)
  <script>window.answerableIdentity = @json($answerableIdentity);</script>
@endisset
```

If someone signs in without a page load, fetch a freshly signed identity from your server and pass it to `answerable.identify(identity)`; on sign out, call `answerable.identify(null)`.

### Keeping it secure

- Sign only on the server, and only the address of the user your server's own session says is signed in. Never sign an address taken from the request (a query parameter, a form field, a header), or anyone could write as anyone.
- Never send the secret to the browser: keep it out of client code, bundles, and public environment variables (like `NEXT_PUBLIC_` or `VITE_` ones), and never commit it. If your project lists its environment variables (like `.env.example`), add `ANSWERABLE_WIDGET_SECRET` there without a value.
- An endpoint that returns a signed identity must require the signed-in session and return only that user's identity.
- Don't serve a page with someone's signed identity in it from a shared cache.
- **New secret** under **Signed-in visitors** replaces the secret at once; signatures made with the old one stop working.
