Skip to the guide

Need help? Your SensibleStats contact can answer questions about any guide and send the three values. Write to solutions@sensiblestats.com.

Highlighted values such as YOUR_PUBLIC_KEY are placeholders. Replace them with the values we send you.

Widget guides / Web script

Chat widget on your website: script tag

Add one <script> tag to your pages and visitors get a chat that answers questions about matches, teams and players, with stats and your prices. This guide covers every setting, callback and object the script tag gives you. If your site is a React or Next.js app, use the React guide instead.

Checklist:

  1. Get your operator id, public key and widget origin from your SensibleStats contact.
  2. Send your contact every origin you test and go live on.
  3. Add the script and pass the signed-in visitor's id.
  4. Set onAddToSlip, then test an add, a duplicate and a reject.
  5. Set onUnavailable, and add our hosts to your Content Security Policy.

1. What your visitors get#

  • A chat icon in a bottom corner, with a teaser beside it: a short greeting about a game, often with one of your prices and a few suggested questions.
  • A chat panel where visitors ask in their own words and get answers as text and cards: stats, form, line-ups, standings and your prices.
  • Add to slip. A price in the chat carries a button that hands the selection to your code (section 7).

Terms used in this guide:

  • Operator id and public key identify your account to our server.
  • Widget origin is the address of our server for your account, shown here as https://your-widget-host.
  • Teaser is the short greeting bubble next to the chat icon.
  • Bet slip (or slip) is the list of selections a visitor collects on your site before placing a bet.
  • Price is your odds for one selection.
  • matchOddsId is your sportsbook's own id for one selection: one outcome of one market.
  • operatorUserId is your id for the signed-in visitor (section 5).

2. Before you start#

You need three values from your SensibleStats contact and must send them one list.

From usExampleWhat it is
Operator idYOUR_OPERATOR_IDYour account in our system. Part of every request.
Public keyYOUR_PUBLIC_KEYIdentifies your widget. Safe to put in page HTML; it only works on your allowed domains.
Widget originhttps://your-widget-hostThe address the script and the chat talk to.
To usExampleWhat it is
Allowed domainshttps://www.example.com, https://staging.example.comEvery origin where the widget runs: scheme and host (and port, if not the default). No paths. A page on any other origin gets no widget.

Test before you go live. Send your SensibleStats contact every origin you test on, including http://localhost:3000 and your staging host. Matching is exact: https://example.com and https://www.example.com are two entries, and wildcards don't work.

3. Add the widget#

The quickest start: paste this before </body>.

HTML
<script
  src="https://your-widget-host/embed.js"
  data-operator-id="YOUR_OPERATOR_ID"
  data-public-key="YOUR_PUBLIC_KEY"
  data-greeting-message="hello"></script>

The icon appears in the bottom-right corner. Every setting in section 4 has a data-* form, so you can configure the widget without writing JavaScript.

Callbacks (add to slip, events, your own launcher) need JavaScript. For a full integration, load the script without the data-operator-id and data-public-key attributes and start it with init():

HTML
<script src="https://your-widget-host/embed.js"></script>
<script>
  function addToSlip(selection) {
    return mySlip.add(selection.matchOddsId)
      .then(function () { return { status: 'added' } })
      .catch(function () { return { status: 'rejected', reason: 'not_found' } })
  }

  var config = {
    operatorId: 'YOUR_OPERATOR_ID',
    publicKey: 'YOUR_PUBLIC_KEY',
    greetingMessage: 'hello',
    page: { sport: 'football', kind: 'match', matchId: 19432556 },
    onAddToSlip: addToSlip,
  }

  function start(userId) {
    return window.SensibleStatsWidget.init(Object.assign({}, config, {
      userContext: { operatorUserId: userId, defaultLanguage: 'en-GB' },
    }))
  }

  var chat = start(currentUser && currentUser.id)
</script>

Names that start with my or My, and currentUser, stand for your own code.

init() returns a handle (chat above) with the methods in section 13, or null when it cannot start (the console says why). Calling init() a second time returns the same handle and logs a warning; call chat.destroy() first to start again.

The script finds the widget origin from its own address, which must end in /embed.js. If you load the file from somewhere else (a copy on your own CDN, your own bundle), set data-base-url or baseUrl to https://your-widget-host; without it the widget logs baseUrl is required and does not start.

4. Settings#

Each row gives the data-* attribute and the init() key. Settings marked JS only have no attribute.

Required#

Attributeinit() keyTypeWhat it does
data-operator-idoperatorIdstringYour operator id.
data-public-keypublicKeystringYour public key.

With only one of the two attributes set, or init() called without operatorId or publicKey, the widget logs data-operator-id and data-public-key are required and does not start.

Only when you host the script file yourself:

Attributeinit() keyTypeWhat it does
data-base-urlbaseUrlURLThe widget origin, https://your-widget-host.

Visitor, language and time#

Attributeinit() keyTypeDefaultWhat it does
data-operator-user-iduserContext.operatorUserIdstringnoneThe signed-in visitor's id in your system. See section 5.
data-anonymous-identityanonymousIdentitybooleantruefalse stops the widget storing a random id for visitors who are not signed in; they then have no favourites. See section 5.
data-languagelocale and userContext.defaultLanguagelanguage tag, e.g. en-GB, tryour account's default language (English unless you asked for another)The language of the chat and its answers.
data-time-zonetimeZoneIANA zone, e.g. Europe/Istanbulthe browser's zoneKick-off times and day names follow this zone. An unknown zone falls back to the browser's.
data-odds-formatoddsFormatdecimal, american, fractionaldecimalHow prices are written. A visitor who picks a format in the chat's settings keeps their choice.

Greeting and page#

Attributeinit() keyTypeDefaultWhat it does
data-greeting-messagegreetingMessagestringnoneThe widget sends this once when the page loads, and the answer becomes the teaser. Use hello. Without it there is no greeting and no teaser.
data-greetinggreetingstringnoneFixed text shown in the teaser while there is no greeting answer.
data-sport, data-page-kind, data-match-id, data-competition-idpagesee section 6noneThe page the visitor is on, so the greeting can lead with it.
data-placeholderplaceholderstringlocalizedText in the empty question box.
data-startersstartersa|b|c / string arraynoneSuggested questions shown in an empty chat.

Look#

Attributeinit() keyTypeDefaultWhat it does
data-themethemelight, dark, autoautoauto follows the visitor's system setting. A visitor who picks a theme in the chat keeps their choice.
data-accent, data-cta, data-surface, data-inkcolors.lighthex coloursee section 10Light theme colours.
data-accent-dark, data-cta-dark, data-surface-dark, data-ink-darkcolors.darkhex coloursee section 10Dark theme colours.
data-logo-urllogoUrlURLour markYour logo, shown on the icon and in the panel header.
data-header-titleheaderTitlestringSensibleStatsThe panel's title.
data-positionpositionleft, rightrightWhich bottom corner the icon sits in.
data-offset-x, data-offset-yoffset: { x, y }number, px20, 20Distance from the side and from the bottom of the window.
data-radiusradiusnumber, px16Corner radius of the panel.
data-launcherlauncherfalseonfalse hides our icon and teaser so you draw your own (section 8).
data-launcher-labellauncherLabelstring"Chat with SensibleStats", localizedThe icon's label for screen readers.
data-pin-iconpinIconpin, star, bookmarkpinThe icon visitors tap to follow a match or price.

Slip, callbacks and events (JS only unless noted)#

init() keyTypeWhat it does
onAddToSlip(selection) => resultAdds a price to your bet slip. Without it prices show with no button. Section 7.
slipSportsarray of basketball, americanfootball, tennisThe sports your onAddToSlip accepts besides football. Section 7.
onTeaser(teaser or null) => voidGives you the teaser to draw yourself. Section 8.
onUnavailable(reason) => voidTells you the chat cannot start. Section 11.
onEvent(event) => voidEvery widget event, for your own analytics. Section 9.
eventText (data-event-text="true")boolean, default falseAdds the visitor's question text to question_asked events. Answer text is never sent.

A value of the wrong type or outside the allowed list is ignored and the default applies.

5. The signed-in visitor#

Pass your id for the signed-in visitor in operatorUserId. Use a random, non-guessable id that never changes for that account and that you map to the customer on your side (a UUID works). Never use a customer number, email address or name: the id comes from the visitor's device, and anyone who knows it can act as that visitor. It must be 1 to 128 printable ASCII characters; any other value is not sent.

With the id, the visitor's chat, followed matches and favourites belong to their account, and the greeting can lead with the teams and markets they bet on.

Visitors who are not signed in can use the chat today. The widget then keeps a random id in the browser (localStorage key ss-w-anon-id) so they can have favourites. Under a consent banner, start with anonymousIdentity: false (or data-anonymous-identity="false"), or pass your own consented id in userContext.anonymousUserId. A signed-in visitor will be required in a later release, as it already is in our mobile apps, so plan for it now.

When the visitor signs in, signs out or switches account, start the widget again with the new id, using start() from section 3:

JavaScript
if (chat) chat.destroy()
chat = start(newUserId) // undefined after sign-out

The new widget shows that visitor's own chat thread if they used it in the last hour, or greets them afresh.

6. The page the visitor is on#

Tell the widget which page it sits on and the greeting leads with that game, competition or sport.

FieldAttributeTypeMeaning
sportdata-sportfootball, basketball, americanfootball, tennisRequired when any page field is set. A match id alone means football.
kinddata-page-kindsection, competition, matchA sport's front page, a competition page, or a match page.
matchIddata-match-idnumber or stringYour sportsbook's id for the match on a match page.
competitionIddata-competition-idnumber or stringYour sportsbook's id for the competition on a competition page.

In a single-page app, call chat.setPage(page) on every route change, or chat.setPage(null) on a page that is about no sport. If the visitor has not typed or tapped anything yet, the widget greets again for the new page (after 300 ms, so quick changes count once). Once they have, a page change does not re-greet.

7. Add to slip#

The chat shows your prices, and with onAddToSlip set, each price gets an "Add to slip" button. This is how a tap reaches your slip:

  1. The visitor taps "Add to slip" under a price.
  2. The widget calls onAddToSlip(selection). selection.matchOddsId is your sportsbook's own id for that selection, so you can look it up directly.
  3. Your code adds that selection to your slip and returns what happened, or a promise of it.
  4. The widget shows the visitor a short note in their language, such as "Added to slip".

You have 10 seconds to answer. No answer in time, an error thrown, or an answer that is not one of the results below counts as a failure: the visitor sees "Couldn't add to slip. Try again."

We don't cancel your handler at 10 seconds, so give your slip call its own timeout under 10 seconds, and don't add the selection after it fires.

What the widget sends: SlipSelection

FieldTypeMeaning
matchOddsIdnumberYour sportsbook's id for the selection. Look it up in your slip.
matchIdnumberYour sportsbook's id for the match.
oddsDecimalnumberThe price the visitor saw, as a decimal. Always set.
odds{ format, text }, optionalThe same price in your account's odds format (not the visitor's own choice), e.g. { format: 'american', text: '+150' }. Absent when we have no text in that format: use oddsDecimal.
quotedAtUtcISO time, optionalWhen that price was last confirmed.
sportbasketball, americanfootball, tennis, optionalAbsent for football.
tourstring, optionalTennis only: the tour the match id belongs to.
conversationId, insightIdstring, optionalWhich chat and which card the tap came from.
displayobject, optionalThe pick in words, for showing only: home, away, kickoffUtc, market, marketLabel, selection, line, player. Never price or settle a bet from these.

What you return: AddToSlipResult

ReturnWhenThe visitor sees (English)
{ status: 'added' } or nothingThe selection is in the slip. You can add slip: { selectionCount, totalOddsDecimal }; it is not shown to the visitor today.Added to slip
{ status: 'duplicate' }It was already in the slip.Already in your slip
{ status: 'price_changed', newOdds: '2.10', accepted: true }The price moved and you added it at the new price. newOdds is the new price as text.Added at 2.10 (was 1.95)
{ status: 'price_changed', newOdds: '2.10', accepted: false }The price moved and you did not add it.Price moved to 2.10 (was 1.95). Tap to add.
{ status: 'rejected', reason, message? }You did not add it. reason is one of the values below.See below
reasonMeaningThe visitor sees (English)
login_requiredThe visitor must sign in first.Sign in to add to your slip
suspendedThe market is suspended.Market suspended
closedThe market or match is closed, e.g. it has started.Your message, else "This selection can't be added."
not_found, limit, unsupportedYou don't know this selection; the slip is full or a limit is reached; you don't take this kind of selection.Your message, else "Couldn't add to slip. Try again."

Other languages show the same notes, translated. message is your own text, shown as is: write it in the visitor's language. It is ignored for login_required and suspended.

An added or duplicate selection shows "In slip" on its button until the page reloads, or until you call chat.slipRemoved for it.

Other sports. Football prices get the button once onAddToSlip is set. Basketball, American football and tennis prices get it only when slipSports lists that sport, so a handler that only knows football never receives them:

JavaScript
slipSports: ['basketball', 'tennis']

For these sports the prices come from our own data, so matchOddsId and matchId are our ids, not your sportsbook's. Find the selection from display (teams, kick-off, market, selection and line) and tour for tennis, and return not_found when you cannot. Branch on sport: a basketball id can equal a football id.

Telling the widget what happened next (optional). These calls help the widget track your slip.

CallWhen
chat.slipRemoved({ matchOddsId, sport? })The visitor removed a selection from your slip, "clear all" included. Clears its "In slip" mark.
chat.betPlaced({ selections: [{ matchOddsId, sport? }], stake?, currency?, betId?, betType?, totalOdds? })The visitor placed a bet. Pass every leg; the widget reports only the ones it added, at most 25.
chat.matchOpened({ matchId })The visitor opened a match page. Counts only after the visitor has opened the chat in that tab, at most once per match every 30 minutes.

Ids must be positive whole numbers; others are ignored, numeric strings included. Echo sport back for a non-football leg. stake and totalOdds must be numbers and currency, betId and betType strings; a field of another type is dropped.

The same methods exist on window.SensibleStatsWidget from the moment the script loads. Calls made before the widget starts are kept (the last 20) and sent once it does. A full page load drops them.

8. The icon and teaser#

By default the widget draws its own icon and teaser. To draw them yourself, in your site's design, set launcher: false and onTeaser before you call start() from section 3:

JavaScript
config.launcher = false
config.onTeaser = function (teaser) {
  if (!teaser) return myLauncher.hideTeaser()
  myLauncher.showTeaser(teaser.text, teaser.asks, teaser.price)
  chat.teaserShown()
}
var chat = start(currentUser && currentUser.id)
myLauncher.onIconClick = function () { if (chat) chat.open() }

onTeaser receives a Teaser when there is one, and null when it is gone. The same value is also sent as a sensiblestats:teaser event on window, with detail: { teaser }.

FieldTypeMeaning
textstring or nullThe greeting line.
asksarray of { index, label }Suggested questions. Show label; pass index to tapAsk.
ctastring, optionalA button label, e.g. "Build a bet".
price{ matchOddsId, marketLabel, label, odds }, optionalOne price: the market's name, the selection's name and the price as text.

Call these when the visitor acts on your teaser:

CallWhenWhat the widget does
chat.teaserShown()You showed the teaser.Counts it as seen.
chat.tapTeaser()The visitor tapped the teaser text.Opens the chat.
chat.tapAsk(index)The visitor tapped a suggested question.Opens the chat and asks it.
chat.tapCta()The visitor tapped the button.Opens the chat on it.
chat.tapPrice()The visitor tapped the price.Checks the price again, then calls your onAddToSlip. Returns a promise of a PriceResult (below), or null when there is no price.
chat.dismissTeaser()The visitor closed the teaser.Clears it; onTeaser(null) follows.

Unlike the slip calls, teaser calls are never kept for later: before the widget starts they do nothing.

PriceResult is { matchOddsId, outcome, text }. text is the note to show the visitor, or null.

outcome is added (the selection is in the slip: added, already there, or added at a new price), gone (the price is no longer offered), cool_off (too many requests; try again shortly) or failed (not added: your handler refused it or did not answer).

On the web our own icon owns the teaser, so with launcher left on these calls do nothing and tapPrice() resolves null.

9. Events for your analytics#

Every visitor action is passed to onEvent and sent as a sensiblestats:event event on window (detail is the event), so you can forward it to your own analytics. An error in your handler never reaches the widget. The widget does not check consent; gate your own sending on it.

Every event carries name, at (epoch ms, when it happened), operatorId and widgetVersion, and when known language, conversationId, operatorUserId, anonymousUserId and page. A ? marks a field that can be absent.

EventFields
launcher_clicknone
widget_opensource? (launcher, bubble, teaser, host, popup), first?
widget_closemethod (button, escape, host for your close(), native, back), tab, answering, openMs?
bubble_shown, bubble_click, bubble_dismissnone
bubble_ask_clickposition
tab_changefrom, to, source? (bar, link, auto)
question_askedturnId, source, length, text? (only with eventText), method?, chipId?, position?, actionRef?, retryOf?, matchId?
answer_receivedturnId, conversationId, latencyMs, cardTypes, firstByteMs?
answer_failedturnId, code
answer_stoppedturnId
add_to_slip_clickmatchOddsId, matchId, odds, market?, sport?, factKey?, surface?, turnId?
add_to_slip_resultthe same fields, plus outcome
pin_clickaction (add, remove), target (match, market), matchId?, market?, sport?, surface?, turnId?
combo_add_clicksurface (builder, chat), sport, legs, total, turnId?
combo_variant_clicksurface, sport, legs, total, variant
combo_swap_clicksurface, sport, legs, total
all_markets_clickmatchId, market?, surface
dashboard_tile_clickentityType, entityId
sport_switchsport
new_conversationnone
favourite_changekind, id, outcome, sport?, surface?, before?

add_to_slip_result.outcome is added, duplicate, price_changed, timeout or the reason you rejected with. timeout covers any failed add, not only a late one. odds in events is always a decimal number.

tab, from and to are one of chat, live, matches, builder, following, trends, games, fixtures, standings, squad, records. question_asked.source is one of typed, starter, action, tile, preset, live_fact, bubble_ask, retry, match_sheet.

10. Colours#

Each theme has four colours. A colour you leave out keeps ours. The dark theme reads only the dark colours, never the light ones.

ColourUsed forLight defaultDark default
accentYour brand colour: the icon, links and highlights.#17936a#37c891
ctaPrice and "Add to slip" buttons.#f5a623#ffb638
surfaceThe panel's background.#ffffff#141b24
inkText.#14181d#e8edf2

Set surface and ink together: the teaser, lines and faint text are then mixed from them.

JavaScript
colors: {
  light: { accent: '#0b5fff', cta: '#ffcc00' },
  dark: { accent: '#5c93ff', cta: '#ffd633', surface: '#0d1117', ink: '#f0f3f6' },
}

11. When the chat cannot start#

When our server refuses the widget, it calls onUnavailable(reason) once. The same reason is sent as a sensiblestats:unavailable event on window, with detail: { reason }. The widget stays on the page, so remove it in your handler: onUnavailable: function () { chat.destroy() }.

reasonCauseFix
widget_disabledThe widget is off for your account, or the operator id is not one we know.Check the id. If it is right, ask your SensibleStats contact to switch the widget on.
auth_failedThe public key is wrong or empty, or the page's origin is not an allowed domain.Check the key; send your contact the origin.

In the browser console, [SensibleStatsWidget] baseUrl is required means the script was not loaded from .../embed.js and no baseUrl was set; data-operator-id and data-public-key are required means one of the two is missing; already started; init ignored means init() was called twice.

12. Platform notes#

  • Content Security Policy. Allow these:
    • script-src: https://your-widget-host, and the script host your SensibleStats contact sends you (the script redirects to a versioned copy there).
    • connect-src: https://your-widget-host.
    • img-src: your logo's host. Your SensibleStats contact sends you the image hosts to allow in img-src.
    • style-src: inline styles, because the widget adds its stylesheet as a <style> element.
    • Optional: style-src https://fonts.googleapis.com and font-src https://fonts.gstatic.com for the games tab's font. Without them a fallback font is used.
  • Styles stay apart. The widget lives in a shadow root under <div data-ss-w-host> at the end of <body>. Your CSS does not change it and its CSS does not change your page.
  • Stacking. The icon and panel use position: fixed and z-index: 2147483000.
  • Small screens. Below 640 px wide the panel fills the screen.
  • Stored data. The widget keeps the chat thread (for one hour after its last change), followed matches, settings and its labels in the visitor's localStorage, under keys that start with ss-w-. The random visitor id from section 5 is there too, unless you turn it off.

13. Reference#

init() returns this handle, or null when it cannot start (the console says why). After destroy() every method does nothing.

MethodReturnsWhat it does
open(), close()nothingOpens or closes the chat panel.
setPage(page)nothingSets the page (section 6); null clears it.
destroy()nothingRemoves the widget from the page.
slipRemoved, betPlaced, matchOpenednothingSection 7.
teaserShown, tapTeaser, tapAsk, tapCta, dismissTeasernothingSection 8.
tapPrice()promise of PriceResult or nullSection 8.

Once the widget has started, open, close, setPage and destroy are also on window.SensibleStatsWidget, for code that cannot reach chat.