Hopp til innholdet

DocumentationChat widgetMarkdown

Visitor widget

The stock chat bubble. One script tag, no build step, no CSS to import.

html
<script src="https://<host>/widget.js" data-tenant="<tenantId>" defer></script>

Requirements:

  1. The page's origin (e.g. https://www.example.no) is listed in the tenant's allowed origins (admin → Settings → Sites that may show the chat, or PATCH /api/v1/operator/tenant { allowedOrigins }). http://localhost:* works outside production.
  2. That's it. Name, portrait, welcome text, suggestions and team come from the tenant settings.

The widget renders inside a shadow root, so your CSS can't break it and its CSS can't leak into your page.

On/off. An admin can hide the widget without touching the site: admin → Settings → Show the chat on the website (or PATCH /api/v1/operator/tenant { "widgetEnabled": false }). Off, the config says widgetEnabled: false and the widget renders nothing (no launcher, no teasers), also for visitors in the middle of a conversation. Open pages pick the change up within a minute; turning it back on brings the launcher back the same way. Live visitor tracking keeps running (it follows Show visitors live and consent, not this switch), so the team still sees who is on the site under Visitors with the chat off. The API, SDK and operator mode are not affected, so a custom UI keeps working unless it checks widgetEnabled itself.

Options (data-* attributes)

AttributeDefaultMeaning
data-tenantrequiredTenant id. (data-kunde is an accepted alias.)
data-positionrightleft puts the launcher bottom-left.
data-openfalsetrue opens the chat on load.
data-languagebrowser languageThe widget's own texts, and the conversation's language until the visitor writes (then the language they write in wins).
data-accenttenant brand colourAccent colour override, #rrggbb.
data-user-name, data-user-email, data-user-phone, data-user-companyWho the visitor is, if your page knows (e.g. rendered by your server for a logged-in user). Same as Snakkbar.setUser(...), see below.
data-operator-tokenStaff only: your operator-token endpoint. Turns on operator mode.
data-operator-inboxhosted panelStaff only: your page with the full inbox (mountAdmin). The overlay's link then reads «Open in new tab» and opens it; without it, «Open in Snakkbar» opens the hosted panel.
data-operator-onlyfalseBack office: show nothing (no visitor chat) when the token endpoint says no.

JavaScript API

js
Snakkbar.open();
Snakkbar.close();
Snakkbar.toggle();

// Switch to an identified visitor (token minted by your backend, see below).
Snakkbar.identify(async () => (await fetch("/api/snakkbar-token")).text());

// Tell Snakkbar who the visitor is (all fields optional; calls are merged).
Snakkbar.setUser({
  name: "Jane Smith",
  email: "jane@example.no",
  phone: "+47 900 00 000",
  company: "Smith Ltd",
  attributes: { customerNo: 1234, plan: "pro" }, // your own fields; null removes one
});

// What the visitor did on your site, for their timeline in the panel and what led to it
// (a newsletter, a chat). See "Shop events" below.
Snakkbar.track("add_to_cart", { value: 1990, currency: "NOK", items: [{ id: "BX-770", name: "Bernina 770", price: 1990, quantity: 1 }] });

// Events: "open", "close", "message" (a stored Message), "unread".
const off = Snakkbar.on("message", (message) => console.log(message.role, message.body));
off();

Snakkbar.destroy(); // remove the widget completely

Mounting by hand (SPAs that load the script without data-tenant, or several tenants on one page):

js
// after <script src="https://<host>/widget.js"> has loaded
const widget = window.Snakkbar.mountWidget({
  host: "https://<host>",
  tenantId: "<tenantId>",
  position: "right",
  user: { name: "Jane Smith", email: "jane@example.no" }, // optional, same shape as setUser
});
widget.setUser({ company: "Smith Ltd" });

A launcher badge shows unread assistant/staff messages while the chat is closed.

Operator mode

When the person looking at the page is logged in as staff, the same launcher becomes their way into Snakkbar, on the public site and in your back office alike:

  • Click the launcher: a quick menu with conversations waiting for a person (longest wait first; ones that ask for this operator on top), Mine (owned or joined, unread first), unread note mentions, and how many chats the assistant is having right now. The header has the Available/Away switch (whether the assistant may hand customers to them) and ⤢.
  • Click a conversation: it opens as a compact chat: the transcript (translated, with notes), a reply box (Enter sends, Shift+Enter new line, Note for an internal note with @name), and Take over, Hand back to (the assistant), Close or Reopen. Replying to the assistant's conversation takes it over.
  • ⤢ opens the full admin (admin.js, loaded only then) over the page, on that conversation, with Open in new tab to your own inbox page (data-operator-inbox), or Open in Snakkbar to the hosted panel when that is not set. The hosted panel opens signed in, with no Snakkbar login: the link hands the operator's current token to /panel/open in the URL fragment (never sent to a server, dropped from the address at once), which trades it for a panel session for the same operator and tenant (POST /operator/panel-session, 12 hours, for that tab only). After that the person opens Snakkbar from the site again, or logs in with their e-mail.
  • It pops up by itself when a visitor asks for a person (for this operator or for anyone), a visitor writes in one of their conversations, or a colleague mentions them in a note: the chat opens next to the launcher without taking keyboard focus (whatever they were typing in your page keeps the keys), and a soft chime plays. If a chat is already open it stays put and the header shows «1 new». New chats with the assistant never pop up; they only count in the menu. Do not disturb in the menu turns off popping and sound (the badge still counts). Chime, blinking tab title and desktop notifications follow the same per-browser choices as the inbox (Settings → Alerts on this device in the inbox).
  • The badge counts waiting + own conversations with unread messages + mentions.
  • Language: staff's quick menu, chat and ⤢ inbox follow their browser: Norwegian when it prefers Norwegian (no, nb, nn), English otherwise. data-language only sets the visitor chat's language, never the operator mode's.
  • Several tabs share one realtime connection and one chime (Web Locks + BroadcastChannel).
  • Page loads: the open panel, the open chat and drafts stay per tab while moving between pages.
  • Presence: a visible page with the launcher counts as being in the inbox, so the operator gets no e-mail or push about what is on screen. Only Available makes the assistant route customers to them.
  • Staff are not visitors: no visitor tracking, proactive messages or greeting in operator mode, so staff no longer show up as live visitors on their own site. View as a visitor in the menu switches the tab to the normal visitor chat (to test it); Back to the operator view in the chat's ☰ menu switches back.
  • Visitors never download any of this: the operator code (/widget-operator.js) loads only after your page handed over an operator token.

Turning it on

  1. A token endpoint on your own site that answers only for logged-in staff: the same exchange as for the embedded admin (admin-embed.md). The widget calls it with POST, credentials: "same-origin" (your session cookie) and Accept: application/json, and expects 200 { token, expiresAt }; 401/403 (or 204) means «not staff» and the normal visitor chat shows. It is called at most about once an hour per tab (the token is kept in sessionStorage until a minute before expiresAt).

  2. On pages rendered for logged-in staff, add the attribute to the widget's script tag. Render it only for staff (server-side), so ordinary visitors never call your endpoint:

    html
    <script src="https://<host>/widget.js" data-tenant="<tenantId>"
            data-operator-token="/api/snakkbar/operator-token"
            data-operator-inbox="/admin/snakkbar"
            defer></script>

    In the back office, where only staff come, add data-operator-only (nothing shows if the endpoint says no) and include the script on every back-office page (the layout template).

  3. The page's origin must be an allowed origin (as for the widget).

By hand: mountWidget({ host, tenantId, operator: { tokenUrl, inboxUrl, only } }), or operator: { token } with your own function returning the token, { token, expiresAt } or null.

js
// Your own menu badge, e.g. «Customer chat (2)» in the back office's navigation.
Snakkbar.on("operator", ({ attention, waiting, mine, unread, mentions, assistant, available }) => {
  badge.textContent = attention ? String(attention) : "";
});

Snakkbar.open(), close() and toggle() drive the quick menu in operator mode. While the widget is in operator mode, identify, setUser and consent are kept for «View as a visitor».

Checks: logged in as staff the launcher shows the badge and opens «Conversations»; logged out (or as a customer) it is the visitor chat and the token endpoint is not called; from another browser, ask for a person on the public site: the chat pops open in the back office within seconds, and the text field you were typing in keeps the focus.

Telling staff who the visitor is

Snakkbar.setUser({ name, email, phone, company, attributes }) (also WidgetController.setUser, MountWidgetOptions.user and the data-user-* attributes) sends what your page knows about the visitor to Snakkbar (PATCH /api/v1/visitor/me). Staff see it on the visitor and their conversations, the assistant doesn't ask for it again, and the callback form is filled in from it.

  • Call it after the widget script has loaded, whenever you learn something (e.g. after login). Calls made before the widget has mounted are queued; calls are merged.
  • After identify(token) it is applied again to the identified visitor. identify(null) (logout) forgets it, so the next anonymous visitor doesn't inherit it.
  • Field rules: api.md. Invalid values are rejected by the API; the widget only logs the error to the console and never throws.
  • It is unverified: anyone can type anything into a browser. For an identified visitor it only fills fields that are still empty and adds attribute keys that don't exist yet; trusted values belong in your backend's token request (POST /server/visitor-tokens takes name, email, phone, company, attributes).

Live visitors

On every page it is on, the widget reports the visitor as a live visitor, also before (and without) a chat: staff see who is on the site now, the current page, the navigation history, device, rough location and where the session came from, in the admin's «Visitors» and «Overview». An operator can open «Watch live» to follow the visitor's cursor, clicks and scroll over the page. This is the SDK's startTracking(); details in realtime.md, and what is and isn't collected in security.md.

The widget does nothing extra for this: no setup, and no visible change for the visitor. Inside an operator's live view (an iframe named snakkbar-mirror) the widget renders nothing and only keeps the page scrolled to where the visitor is.

Switch. Live visitors are on by default. An admin turns them off per tenant under Settings (or PATCH /api/v1/operator/tenant { "liveVisitors": false }). Off, the widget sends nothing and creates no visitor until someone opens the chat; staff then only see visitors who chat.

Consent. Live visitors track behaviour on the site (pages, and the cursor while watched) and store a visitor token in localStorage for every browser that opens a page. In many jurisdictions (e.g. the EU/EEA under GDPR and the ePrivacy rules) that needs the visitor's consent unless your site has another legal basis. If your site needs consent for this kind of tracking, do one of:

  • No consent mechanism, or you don't want the tracking: turn liveVisitors off. The chat works as before; nothing is sent until the visitor opens it.

  • Consent banner: load the widget only after the visitor has consented (statistics/analytics category, or whatever your banner calls it), and mention Snakkbar in your privacy notice:

    js
    // e.g. in your consent manager's "accepted" callback
    function loadSnakkbar() {
      if (window.Snakkbar?.open) return;
      const s = document.createElement("script");
      s.src = "https://<host>/widget.js";
      s.dataset.tenant = "<tenantId>";
      document.body.appendChild(s);
    }

    Visitors without consent then have no chat either. If they should still be able to chat, turn liveVisitors off instead: the switch is per tenant, not per visitor.

Whether consent is required is the site owner's call; Snakkbar gives you the switch and keeps the data minimal.

Identified visitors

By default every browser is an anonymous visitor. If your site has logged-in users, let the chat follow them across devices and show staff who they are:

ts
// Your backend (never expose the secret key in the browser)
const res = await fetch("https://<host>/api/v1/server/visitor-tokens", {
  method: "POST",
  headers: { authorization: `Bearer ${process.env.SNAKKBAR_SECRET_KEY}`, "content-type": "application/json" },
  body: JSON.stringify({ externalId: user.id, name: user.name, email: user.email, phone: user.phone, company: user.company }),
});
const { token } = await res.json(); // valid 24 h; send it to the browser

Then Snakkbar.identify(token) (or a function returning a fresh token). Call identify(null) on logout to return to an anonymous visitor.

Logging in keeps the visit. When a browser that was anonymous is identified, the anonymous visitor becomes the identified one: its pages, chats (the open one stays open), campaign visits and events move over, and where the visit came from (a newsletter link, an ad) stays with it. Staff watching the anonymous visitor are moved along to the identified one. This happens once, on the identified visitor's first request; the anonymous visitor is then forgotten on the device. On a shared computer, what the previous anonymous user did in that browser goes along too, as in most analytics tools.

Shop events

Snakkbar.track(name, { value?, currency?, transactionId?, items?, properties? }) records something the visitor did. Staff see it in the visitor's timeline (Besøkende → Navigasjon), between the pages, with the amount, the products and what led to it: a campaign link visited within the last week, a chat in the same visit. Milestones (checkout, payment, refund) also go on the contact.

NameWhen
view_itemA product page or quick view
add_to_cart / remove_from_cartThe cart changed (items, and the cart's value)
begin_checkoutThe checkout opened
add_payment_infoA payment method was chosen
purchaseThe payment succeeded (transactionId = your order id)
payment_failedThe payment failed
refundMoney back

Any other snake_case name (up to 40 characters) is yours, e.g. booked_demo. items are { id?, name?, category?, price?, quantity? } (up to 50), currency an ISO code like NOK, properties up to 30 of your own plain values. Events follow the same consent as tracking: while consent is needed and not given, nothing is sent.

What only your backend knows for sure, such as the payment provider's confirmation, is best sent from there: POST /api/v1/server/events (api.md). With the same transactionId the browser's report and the backend's count once.

Look and behaviour

  • Colours come from your page: shadcn/ui CSS variables on <html> if present, otherwise the page's background and text colours, with the tenant's brand colour (or data-accent) as accent. Light and dark pages are handled, and the widget follows live theme switches.
  • Launcher: shows the face of a staff member who is online (with a green dot), otherwise the assistant's portrait.
  • Desktop: a 440×720 popup in the corner. Visitors can resize it by dragging the top edge, the side edge or the corner; the size is remembered, and double-clicking a handle resets it.
  • Mobile (≤700 px): a full-screen sheet with a grab bar; keyboard-aware.
  • Chats: the ☰ menu lists the visitor's earlier conversations and starts a new one.
  • People: the team row and @name reach staff; the assistant hands over when asked.
  • Images: up to 4 per message (JPEG, PNG, WebP, GIF; 5 MB each).
  • Translation: messages in other languages show translated, with «Show original».
  • Navigation: staff can move the visitor to another page on the same site.
  • Respects prefers-reduced-motion. Escape closes.

Content Security Policy

If your site sends a CSP, allow:

script-src https://<host>;
connect-src https://<host>;   # operator mode: also your own token endpoint ('self')
img-src https://<host> https://*.supabase.co data: blob:;
style-src 'unsafe-inline';

For the operators' live view («Watch live») your pages must also let the Snakkbar admin frame them: frame-ancestors 'self' https://<host> (plus the origin of your own admin if you embed it), and no X-Frame-Options header that excludes those origins. Without it the live view shows a schematic page instead. See admin-embed.md.