LogoLogo
Back to studio
  • 🧠Core Concepts
    • Introduction to Formsort
    • Formsort quickstart guides
      • Add content and collect answers
      • Capture demographic data
      • Add informational content
      • Template your variables
      • Add conditional logic
      • Using conditional logic with Calculated and API variables
      • Add a scheduling option
      • End the flow
      • Review your variable schema
      • Set up integrations
    • How data works in Formsort
      • Responder UUIDs
    • Understanding flows
    • Versioning in Formsort (Deploying)
      • Variant revisions
      • Managing revisions
  • ✨Creating Flows
    • Building a new flow
      • Groups
      • Steps
      • Copy-pasting form content
  • Adding questions and content
    • Questions
      • Select
      • Text
      • Address
      • Comparison
      • Confirmation
      • Date
      • Date & time
      • Email address
      • File upload
      • Grid choice
      • Iframe
      • Image upload
      • Number
      • Payment
      • Phone number
      • Postal code
      • Question group
      • Region
      • Signature
      • SSN
      • Yes/No
    • Content
      • Statement
      • Image
      • Next button
      • Video
      • Divider
      • Map
  • Controlling the flow with conditions and logic
    • Advanced logic
  • Variable templating
  • Redirects and endings
  • Field validation
  • Flow and variant management
  • Content library
  • 🧬JSON Form Definition
  • JSON schemas
  • Validating flow schemas
  • Events subscriptions
  • Flow content data format
  • 🎨Styling
    • Customizing appearance
      • Content area & form layout
      • Buttons
      • Typography
      • UI states
      • Color and dimension variables
      • Question containers
      • Inputs and dropdowns
      • Checkmarks
      • Tables
      • Sliders
      • Divider lines
      • Progress bar
      • Comparison cards
      • Animations and transitions
  • CSS & Advanced Styling
    • Custom CSS overrides
    • Step styling
    • CSS reference
  • 🔁Form Behavior Settings
    • Variant settings
      • Form behavior for returning users
      • Group ranking API
    • Navigation sidebar
  • ⚙️Response Data Collection & Management
    • Schema (variables)
      • Variables from questions
      • Externally provided variables
      • Calculated variables
      • API lookups
      • System Library variables
      • Orphaned variables
  • Saving & retrieving responses
  • Importing Data
    • URL parameters
    • POST body
    • Embed query parameters
  • 📊Analytics and Attribution
    • Built-in analytics
    • Split testing
  • 🚀Publishing and Deployment
    • Live preview overview
    • Environments
      • Loading different environments
    • Embedding
      • Web-embed API
        • React-embed
      • Adding authentication
      • Embedding forms in iOS and Android
      • Setting up a dev environment
    • Pre-deployment checklist
  • 📁Workspace Management
    • Accounts
      • Roles and permissions
    • Custom domains
    • Workspace domain detection
  • 🛠️Formsort Admin API
    • Admin API
  • 🔌Integrations
    • Form answers and events
      • Analytics events
      • Signed requests
      • Event payload shape
      • Submission frequencies
      • Runtime error reporting
    • Integration reference
      • Amplitude
        • Amplitude cross domain tracking
      • BigQuery
      • FullStory
      • Google Analytics
        • Updating from Universal Analytics to GA4
      • Google Cloud Storage
      • Google Sheets
      • Google Tag Manager (GTM)
        • JavaScript triggered by flow events
      • Hubspot
      • Jornaya
      • Optimizely
      • PostgreSQL
      • Redshift
      • Rudderstack
      • S3
      • Salesforce
      • Segment
        • Segment Setup
        • Segment cross domain tracking
      • Stripe
      • TrustedForm
      • Webhooks
        • Zapier
Powered by GitBook
On this page
  • Usage
  • Documentation
  • Development

Was this helpful?

  1. Publishing and Deployment
  2. Embedding

Web-embed API

Embed your flows within other webpages, with communication between the embed and the parent page

PreviousEmbeddingNextReact-embed

Last updated 8 months ago

Was this helpful?

The Formsort Github repository can be found at .

If you're using React, see which is a handy wrapper around the web-embed-api.

Once you are finished writing your web-embed-api code, check out our doc to begin testing the embed in your webpage.

Usage

First, install:

# yarn add @formsort/web-embed-api
# npm install @formsort/web-embed-api --save

Then, initialize the embed and load a flow.

Documentation

FormsortWebEmbed(rootEl: HTMLElement, config?: IFormsortWebEmbedConfig)

Initializes a Formsort iframe as a child of the rootEl provided.

const embed = FormsortWebEmbed(document.body);

The optional config object has the following interface:

interface IFormsortWebEmbedConfig {
  useHistoryAPI?: boolean; // Default: false
  autoHeight?: boolean; // Default: false
  style?: {
    width?: CSSStyleDeclaration['width'];
    height?: CSSStyleDeclaration['height'];
  };
  authentication?: {
    idToken?: string; // ID Token for authenticated flows
  };
}

config properties

  • useHistoryAPI: When redirecting, should we use the HTML5 History API (namely, window.pushState), or just change the URL in its entirety?

    Helpful if you have a single-page app and want to change the container's URL without reloading the entire page. Note that you'll have to listen to the popstate event on the embedding window to detect this navigation.

  • autoHeight: Should the embedding <iframe> resize so that it matches the content of the currently loaded flow?

  • style: CSS properties to be applied to the iframe container.

  • authentication.idToken: When the Flow requires an ID token, this can be used to provide it.

loadFlow(clientLabel: string, flowLabel: string, variantLabel?: string, queryParams?: Array<[string, string]>) => void

// Ex (w/o query parameters):
embed.loadFlow('formsort', 'onboarding', 'main');

// Ex (w/ query parameters):
embed.loadFlow('formsort', 'onboarding', 'main', [['utm_medium','social']]);

Starts loading a Formsort variant, or a flow.

Note that variantLabel is optional. If it is not provided, a variant will be chosen from the flow:

  • At random, if no weights are assigned

unloadFlow() => void

Remove inserted iFrame and all its event listeners.

setSize(width: number, height: number) => void

Set the CSS size of the embed.

You may also style the embed's iframe using CSS - it is the iframe child of the rootEl, so you'd use the selector #rootEl > iframe.

Event listeners

embed.addEventListener(eventName: key of IEventMap, fn: IEventMap[eventName]) => void

The events include:

FlowLoaded (answers?: { [key: string]: any } ) => void

Set a callback function to be called when the Formsort flow has loaded completely.

Note that this is more accurate than listening for the iframe's load event, as this is sent from within the Formsort application code and not merely when the DOM is loaded.

You can listen for this to do things like hide the frame container, or display a loading indicator, until everything is loaded to ensure a seamless initial experience.

// Ex: 
const embed = FormsortWebEmbed(document.body);
embed.addEventListener('FlowLoaded', () => {
  console.log('Flow has loaded!');
});
embed.loadFlow('formsort', 'onboarding', 'main');

FlowFinalized (answers?: { [key: string]: any }) => void

Set a callback to be called when the flow is complete, meaning the user has finished all of the steps available to them.

Useful for performing an action after the flow is complete, such as displaying a congratulations or starting a payment process.

FlowClosed (answers?: { [key: string]: any }) => void

Set a callback to be called when the user abandons the flow before finalizing it.

Note that this is only possible if your style set defines a close button.

StepLoaded (answers?: { [key: string]: any }) => void

Set a callback to be called when a new step is loaded.

This will happen once after the flow is loaded, if the user hasn't previously completed the flow. Subsequently, this event will happen following the completion of each step, except for the completion of the final step.

StepCompleted (answers?: { [key: string]: any }) => void

Set a callback to be called when a step is completed. This includes the completion of the final step, before the "FlowFinalized" event.

redirect ({ url: string, answers?: { [key: string]: any } }) => ({ cancel?: boolean }) | undefined

Set a callback to customize the way Formsort handles redirects. To cancel Formsort's handling of the redirect, return:

{
  cancel: true;
}

If the callback does not return a value, Formsort will handle the redirect as usual.

This is helpful if you're embedding Formsort within a single-page app that has custom URL route handling.

unauthorized () => void

Set a callback for unauthorized Formsort messages.

This callback is used when the Formsort Flow is authenticated but the ID token is missing or invalid.

Development

By default, the web embed accesses the production formsort servers. If you would like to point to another flow server, set origin in the config to the correct base URL, for example:

FormsortWebEmbed(document.body, { origin: 'http://localhost:4040' });

Based on (e.g. variant split testing), if weights are assigned

If the flow is embedded in a domain, each event listener will be passed the user's answers.

🚀
@formsort/web-embed-api
@formsort/react-embed
Setting up a dev environment
weights
whitelisted