JavaScript API and events

The quote form's methods, its callbacks, prefill, provenance and consent, and how it works with the webchat and form guide.

JavaScript API#

The script adds window.Subcontext.Quote:

Member What it does
Subcontext.Quote.init(options) Starts a form and returns it (see below). Throws an error straight away if container, productSlug or journeySlug is missing, if neither key nor getToken is given, or if the container can't be found.
Subcontext.Quote.enable() Calls enable() on the form from the most recent init().
Subcontext.Quote.disable() Calls disable() on that form.
Subcontext.Quote.destroy() Calls destroy() on that form and forgets it.
Subcontext.Quote.mountAll(root?) Starts a form in every data-subcontext-quote placeholder inside root (default: the whole page) that hasn't started yet, and returns them. You only need this to start placeholders sooner, or after setting their attributes late.
Subcontext.Quote.version The script's version, as a string.

The form that init() returns has these methods:

Method What it does
enable() Shows a disabled form again where it left off. For a form started with enabled: false, starts it. Returns a promise.
disable() Hides the form and closes its live connection. Answers and options are kept.
restartApplication() Forgets the application in progress (and the chat conversation, if any) and goes back to the first page, like the "Start a new application" link.
destroy() Empties the container and closes the connection.

If you have several forms on one page, keep each one init() returns and call its own methods.

Resuming. The form stores the application in progress for each browser tab (in sessionStorage, per product and journey), so reloading the page picks up where the visitor was. Use fresh: true to start over instead.

Address parameters. The form reads these from the page address when it starts. Don't strip them from your URLs:

Parameter What it's for
?quote_id=...&sc_app=... Opens that quote directly (the link in quote emails). sc_app is the signed proof that the visitor may open it. The quote id on its own opens nothing.
?sx_quote=...&sx_intent=...&redirect_status=... Coming back from a card check by the bank (3-D Secure). The form finishes the purchase.
?sx_prelink=... Starts linked to a signed-in customer (from links Subcontext sends). Removed from the address straight away.
?ol=... Opened from an email Subcontext sent. The form starts fresh, fills in what is known and greets the person in the chat. Removed from the address straight away.

Callbacks and events#

The form reports what happened through callbacks only. It doesn't fire its own DOM events.

Callback What you get
onLoad() Nothing. The first page is showing.
onStageComplete(stageType, data) stageType is the kind of page the visitor just left: customer, soft-identity, cover, questions, quote-checkpoint, interstitial, handoff, reflection, market-quote or provider-handoff. data has stagePosition, town (the town from a postcode lookup, if any) and customer.
onQuote(quote) The quote as the API returns it. It includes id, reference, currency_code, total_premium_monthly_pence (in whole pence), components and expires_at. On a group plan, each component also has its title and member_count (see Group plans).
onDecline(executions) A list; each item may have decline_reasons.
onReferred(executions) A list; each item may have referral_reasons.
onBound(policy) The policy as the API returns it. It includes policy_number, commencement_date, currency_code and total_premium_monthly_pence.
onNewApplication() Nothing.
onError(error) error.message. Errors from Subcontext also have status (the HTTP status), code and body. A timeout has status: 0 and code: 'timeout'.

If your code throws an error inside onStageComplete or onNewApplication, the form catches and logs it, and carries on.

Sending callbacks to your analytics. If you'd like DOM events, fire your own from a callback:

js
onStageComplete: (stageType, data) =>
  window.dispatchEvent(new CustomEvent('subcontext:stage-complete', { detail: { stageType, data } }))

The form listens for one event, subcontext:application-ready on window, with detail { id, share_token, customer, risk_factors }. The webchat sends it when its assistant starts an application. The form takes that application over and fills in what the assistant collected. Your page can listen for it too.

In the framed look, the close and "ask" buttons do nothing by themselves. Handle the clicks on your page:

js
document.addEventListener('click', (event) => {
  if (event.target.closest('[data-sx-frame-close]')) document.getElementById('quote-dialog').close()
})
What How Where it ends up
Details you know about the visitor initialCustomer Saved to the customer record when the details page is saved.
Answers initialValues Saved with the application when each page is saved.
Where the visit came from (provenance) Automatic. When the form starts an application it sends the page address (without the # part), the referrer, the page title, whether the form is inside an iframe (and the top page's origin), the browser's language and the time zone. Kept with the application and its lead, so you can see where each quote came from.
Campaign links (UTM) and ad clicks Automatic, from the page address: utm_source, utm_medium, utm_campaign, utm_term, utm_content, utm_id, and click ids gclid, gbraid, wbraid, fbclid, msclkid, ttclid, li_fat_id. With the application's provenance.
Campaign Automatic with a key. The quote form's campaign, and the quote form's results in the dashboard.
Marketing consent The visitor ticks the boxes your firm set up. Recorded with the customer's details and the application.
Chat information chatContext Passed to the webchat conversation.

There's no option to pass UTM values yourself. Keep them in the page address and the form picks them up. If your site removes them from the address before the form starts, they won't be recorded.

A prefill example:

js
Subcontext.Quote.init({
  // ...container, apiBase, key, productSlug, journeySlug...
  initialCustomer: {
    first_name: 'Sam', last_name: 'Taylor', email: 'sam@example.com',
    phone_number: '07700 900123', dob: '14/03/1988', postal_code: 'SW1A 1AA'
  },
  initialValues: { __sumAssured: 15000000, __term: 20 } // £150,000 over 20 years
})

The form shows the consent choices your firm has set up on the dashboard's Consent page. They can appear in two places:

  • On the details page, as "tick if you'd rather not hear from us" boxes. Only a tick is sent (as a "no"); a box left alone records nothing.
  • After purchase, as a marketing question ("Keeping in touch"), and on whole-of-market comparisons before the results.

Consent needs no code. If you're not sure how your consent choices are set up, ask Subcontext.

Working with the webchat and form guide#

Webchat. The form and the chat share one application:

  • When the form starts an application, it tells the chat which product, journey and page the visitor is on (plus your chatContext), so the chat's assistant knows where they are.
  • If the chat's assistant starts the application first, the form takes it over.
  • Answers the assistant records appear in the form live, except in a field the visitor is typing in.
  • Starting a new application in the form also starts a new chat conversation.

Load the webchat yourself as its own guide describes, or pass the webchat option to have the form load it. The webchat option takes:

  • src (required): the webchat script, https://js.subcontext.com/webchat-latest.js.
  • supported (required): must be true, or the chat isn't loaded.
  • Optional: agentId, baseUrl, title, primaryColor, backgroundColor, accentColor, fontSize, theme, defaultOpen, defaultExpanded (default true), launcherIcon, variant, brand, conversationStarters, omni, startUnread, freshConversation, openedFrom, quoteLink, launchAnimation, introText. These are passed straight to the webchat; its guide explains each one.
  • Example 07 shows the form and the chat together.
  • The form's own theme is passed on too. Any theme key you set here, in theme or as primaryColor, accentColor, backgroundColor or fontSize, wins over the form's.

Form guide. The formGuide option loads the form guide and adds its help to the form's fields. It loads after the first page appears; if it fails, the form carries on without it. It takes:

  • agentId (or the top-level agentId).
  • Optional: src (default https://js.subcontext.com/formguide-latest.js), baseUrl, primaryColor, mode ('popover' or 'inline'), exclude (a CSS selector for fields to skip), fieldIcon, and theme (the form guide's panel settings: heading, background, border, margin, inputBackground, inputBorder, inputPadding, buttonBackground, buttonColor, plus the shared theme keys).
  • The form's own theme is passed on too. Any theme key you set here, in theme or as primaryColor, wins over the form's.

Stuck, or something missing?

Get in touch and a person on the team will help.

Contact us