JavaScript SDK

Getting Started

Overview

The Sprig Javascript SDK, when installed in your website or web app, allows you to track your customer’s in-product behavior and display Sprig studies when they perform certain actions. To learn more about SDKs and web installation options provided by Sprig, click here.

Requirements

  • Join your teammates on Sprig (check with your Sprig admin whether team discovery is on, or simply have a team member invite you via your email address). This will give you access to your team’s environment IDs, as well as the interactive Installation Guide.
  • Ensure you have access to your web codebase, and can deploy to a development and/or production environment

Install SDK

If you are installing the Sprig Javascript SDK, we recommend installing Sprig via the HTML code snippet. This installation method automatically ensures you have the latest version of our SDK, reducing the workload on your engineering team since they won’t have to fetch and deploy an update every time Sprig releases a new version of the SDK. You will automatically have access to the latest features on the latest SDKs.

For teams that prefer to use a package manager, Sprig can also be installed via npm or Yarn. Note that your engineering team will need to do some additional work to update in order to access the latest features and bug fixes.

Obtain an Environment ID

Sprig provides two environments, Development and Production, each with its own corresponding ENVIRONMENT_ID (which can be found in Integrations > Javascript SDK).

The Development environment is recommended for initially setting up and verifying your installation. Then, you can use the Production environment to deploy studies to real users.

Install with HTML (recommended)

Add the following JavaScript snippet to every page on your website where you want Sprig to track your users. You can paste the snippet anywhere on the page, but preferably at the bottom of the document, before the </body> tag. Be sure to swap in the correct ENVIRONMENT_ID.

<script>
   (function(l,e,a,p) {
     if (window.Sprig) return;
     window.Sprig = function(){S._queue.push(arguments)}
     var S = window.Sprig;S.appId = a;S._queue = [];window.UserLeap=S;
     a=l.createElement('script');
     a.async=1;a.src=e+'?id='+S.appId;
     p=l.getElementsByTagName('script')[0];
     p.parentNode.insertBefore(a, p);
   })(document, 'https://cdn.sprig.com/shim.js', 'ENVIRONMENT_ID');
 </script>

This snippet fetches the latest version of the SDK asynchronously when the page is loaded. Click here for more information on performance.

Install with npm/Yarn

Use the following shell command to install the Sprig SDK through npm or YARN. With this installation method, Sprig will be bundled with the rest of your front-end application and be immediately accessible on page load.

Note that you will have to update the SDK manually to receive the latest functionality. We recommend you update the package monthly for improved functionality and bug fixes.

npm install --save @sprig-technologies/sprig-browser
yarn add @sprig-technologies/sprig-browser --latest

Then, in your application, initialize Sprig with your ENVIRONMENT_ID:

import { sprig } from '@sprig-technologies/sprig-browser';

export const Sprig = sprig.configure({
  environmentId: 'ENVIRONMENT_ID',
})

Other parameters for configure can be found below in the Customize Appearance section.

Updating the Sprig SDK with npm or Yarn

When using npm or Yarn, you should regularly update your Sprig installation with the latest features by running the following command:

npm update @sprig-technologies/sprig-browser
yarn update @sprig-technologies/sprig-browser

CSP Configuration

Using Sprig for Web studies may require you to update your web application's Content Security Policy (CSP). This may be required because Sprig uses third-party libraries to support JavaScript.

The following list of sources is required to use Video & Voice questions:

  • Base64 SVGs and fonts.
  • Connecting to Mux (for streaming and short video uploads).
  • Connecting to Google APIs (for long video uploads).

Examples are shown in the following CSP source list:

<meta
     http-equiv="Content-Security-Policy"
     content="connect-src blob: data: https://api.sprig.com https://cdn.sprig.com;
     font-src data:;
     worker-src blob:;"
   />
<meta
     http-equiv="Content-Security-Policy"
     content="img-src data: https://*.mux.com;
        connect-src blob: data: https://api.sprig.com https://*.mux.com https://storage.googleapis.com https://cdn.sprig.com https://cdn.userleap.com;
        font-src data:;
        media-src blob: https://*.mux.com;
        worker-src blob:;"
   />

📘

Info

As every company has different security policies, the example may not reflect the complete configuration. You may need to add additional keys and values in order to comply with your own organization’s policies.

Verify Installation

  1. Load a page from your website/web app that has the Sprig SDK installed
  2. Open the developer console to the Network tab
  3. Find a network request named config that hits https://api.sprig.com/...
  4. Check the status code of the request. If it’s 200 or 304, your install is working correctly and you can move on.

Identify Users

Each time a user is tracked by Sprig on a webpage with the SDK installed, they are assigned a unique visitor ID in Sprig that allows users to be targeted with studies when they perform specified behaviors.

While this is a requirement for targeting users with Sprig studies, these are still considered unauthenticated users until their Sprig visitor IDs are coupled with the unique USER_IDs assigned to users within your platform’s internal authentication framework.

We recommend that you follow this best practice when installing Sprig:

  • This ensures consistency between the visitor IDs generated by Sprig and the ones in your internal database, product analytics/CDP, or data warehouse, allowing more effective targeting of studies.
  • Your users have a consistent experience across platforms, and do not see the same study multiple times.
  • It also optimizes the number of Monthly Tracked Users (MTUs) sent to Sprig, which impacts your billing.

If necessary, you can also use an anonymizing function or hash.

A good User ID is…

  • Unique: Two users should not share the same User ID.
  • Mappable: User IDs sent to Sprig should map back to your internal User IDs, either directly or anonymously.
  • Static: Once assigned, a User ID should not change.

Users that do not have a User ID set are considered unauthenticated.

Set User ID

You can use setUserId to identify a user with any string less than 256 characters. This function can be called multiple times safely, and stores the identifier via local storage. We recommend you set the User ID whenever the user logs in to your website, as well as after the installation snippet (if the user is already logged in).

<script>
    Sprig('setUserId', 'USER_ID');
</script>
// import the client returned from your Sprig.configure call
import { Sprig } from 'utils/sprig'

Sprig.setUserId('USER_ID');

Logout

When a user logs out of your webpage, make sure to log out of Sprig. This will prevent new activity from being associated with an incorrect user. Note that if you call logoutUser() on an unauthenticated user, Sprig will assign them a new profile and count this new user separately toward your MTU limit.

<script>
    Sprig('logoutUser');
</script>
// import the client returned from your Sprig.configure call
import { Sprig } from 'utils/sprig'

Sprig.logoutUser();

Track Events

Sprig uses events to trigger (display) studies after the user performs a specific action. They can also be used as a filter to target users who have previously performed an action.

Once you’ve installed the Sprig SDK, the next step is to configure the tracking of events that you would like to use to trigger a study. Sprig provides two types of Events for triggering and filtering your studies, Code and No-Code events.

No-Code Events

No-Code events let teammates without access to the codebase create events in Sprig based on the page’s URL, HTML elements, or CSS, which can then be used to trigger or filter Web studies. No-code events tend to be used to define more straightforward user actions, like viewing a page or clicking a button. For more information, see No-Code events.

Code Events

Sometimes No-Code events may not provide visibility into a particular event that you would like to track. For example, you may want to study users who, in the previous month, have downgraded their account status from premium to standard. It may be preferable to generate the event directly from the webpage.

To track a Code event, you will need the following snippet. You can also optionally attach properties to your event.

<script>
  // Note: all of these functions make a network call, so be sure to give them enough time to complete
  
  // RECOMMENDED: Track event with payload. Only eventName is required.
  Sprig('identifyAndTrack', {
    eventName: 'EVENT_NAME',
    userId: 'some_user_id',
    properties: { property1: 'value'}
  });
    
  // ALTERNATIVES
  
  // Track event with string
  Sprig('track', 'EVENT_NAME');
  
  // Optionally include properties
  Sprig('track', 'EVENT_NAME', { property1: 'value' });
})
</script>
// import the client returned from your Sprig.configure call
import { Sprig } from 'utils/sprig'

// Note: all of these functions make a network call, so be sure to give them enough time to complete

// RECOMMENDED: Track event with event payload. Only eventName is required.
Sprig.identifyAndTrack({
	eventName: 'EVENT_NAME',
	userId: 'some_user_id',
	properties: { property1: 'value'}
});

// ALTERNATIVES

// Track event with string
Sprig.track('EVENT_NAME');

// Optionally include properties
Sprig.track('EVENT_NAME', { property1: 'value' };

After sending a new Code event to Sprig, you must approve the new event request on the Events page before it can be used as a trigger or filter.

These events will also be available as filters for your studies. For example, you may want to only display a study to users who have performed the "checkout" event at least 3 times.

Alternatively, after sending each tracking event, you can decide if a survey should be shown for the user if there is an eligible survey. The optional parameter accepts an async function that expects a boolean. We include the eligible survey ID as the parameter.

<script>
  Sprig('identifyAndTrack', {
    eventName: 'EVENT_NAME',
    showSurveyCallback: async (surveyId) => {
      const shouldShowSurvey = await determineToShowSurvey(surveyId);
      return shouldShowSurvey;
    },
  });
</script>

Track Attributes

Sprig allows you to track attributes, which can provide more context about the user to help you better understand their feedback. You can also use these attributes to filter your audience and target specific kinds of users. Some example attributes that can be tracked are:

  • Plan type
  • Super users / power users
  • Company

A user’s attributes can be seen on their profile in the People page, and are recorded and attached to any response they submit. For more information, see Attributes.

To set a user’s attribute, provide the SDK with a key-value pair:

  • ATTRIBUTE_NAME must be a string less than 256 characters, and cannot start with an ! (these names are reserved for use by Sprig)
  • ATTRIBUTE_VALUE must be a number, boolean, or string less than 256 characters
<script>
    // for a single attribute
    Sprig('setAttribute', ATTRIBUTE, VALUE);
    
    // for multiple attributes
    // saves multiple round-trips and reduces data usage
    Sprig('setAttributes',{
        ATTRIBUTE1: VALUE1,
        ATTRIBUTE2: VALUE2
    });

    // if attributes no longer apply to the user,
    // you can delete multiple at a time
    Sprig('removeAttributes', [ATTRIBUTE1, ATTRIBUTE2]);
</script>
// import the client returned from your Sprig.configure call
import { Sprig } from 'utils/sprig'

Sprig.setAttribute('ATTRIBUTE', 'VALUE');

// for multiple attributes
// saves multiple round-trips and reduces data usage
Sprig.setAttributes({
  ATTRIBUTE1: 'VALUE1',
  ATTRIBUTE2: 'VALUE2'
});

// if attributes no longer apply to the user,
// you can delete multiple at a time
Sprig.removeAttributes(['ATTRIBUTE1', 'ATTRIBUTE2']);

Set Email Address

Setting the user’s email address is optional. Setting emails is not required for web or mobile studies, but can be used to target users or create a Group of users based on their email. Check your organization's guidelines around personally-identifiable information before sending email addresses to Sprig.

<script>
    Sprig('setEmail', 'EMAIL_ADDRESS');
</script>
import { Sprig } from 'utils/sprig'

Sprig.setEmail('EMAIL_ADDRESS');

Test & Deploy

To confirm everything is working as expected with survey, you can create a survey and manually trigger delivery from the Developer Console.

  1. You'll first need to create a Study and set the delivery method to Web. If you're testing in the Development environment, you'll need to create the Study in Development.
  2. In the Sprig app, go to Settings > Configure and select Allow Manual Study Display (on by default for the Development environment)
  3. Open the developer console and run Sprig('displaySurvey', SURVEY_ID);. The SURVEY_ID of a study can be found at the end of its URL (https://app.sprig.com/surveys/SURVEY_ID).
  4. If the Sprig snippet is already installed on that page, your browser will display the study.
    1. If the questions are not rendering correctly or responses aren’t uploaded, check your browser console for any errors. You may have to work with your engineering and security teams to update your installation or CSP settings to resolve the errors.

After you have finished your testing, consider returning to Settings > Configure and select Disable Manual Study Display. This will prevent any other visitor from using displaySurvey in your environment.

Congratulations! Your installation is complete and you can begin deploying.

Advanced Customization

Customize Appearance

You can set a hard limit on the height of your study with the maxHeight parameter, which sets the maxHeight property of the iframe.

For custom installations, if Sprig is installed within an iframe that initially has 0 width, by default, studies will render with desktop styling and a width of 360px. In these cases, to make use of mobile styling and full-width studies on mobile web, you can provide your window dimensions when Sprig is initialized, and when the window is resized, with the setWindowDimensions function.

Example of configuring maxHeight and using setWindowDimensions:

<script>
    // at end of installation snippet 
    Sprig.maxHeight = '50%';  // sets maxHeight property of the iframe to 50% of page height.

    // at end of installation snippet, and when the window is resized
    Sprig('setWindowDimensions', [[WIDTH]], [[HEIGHT]])  // [[WIDTH]] and [[HEIGHT]] are pixel numbers
</script>
import Sprig from '@sprig-technologies/sprig-browser';
// or with require() syntax:
// const sprig = require('@sprig-technologies/sprig-browser');

export const Sprig = sprig.configure({
  environmentId: '[[ENVIRONMENT_ID]]',
  maxHeight: '50%',  // sets maxHeight property of the iframe to 50% of page height.
});

// during initialization, and when the window is resized
Sprig.setWindowDimensions([[WIDTH]], [[HEIGHT]])  // [[WIDTH]] and [[HEIGHT]] are pixel numbers

You can further customize study placement and appearance in our dashboard: Settings > Look and Feel. See Study look and feel documentation for more details.

Sandbox implementation

A common use case from our customers is to place the UserLeapKit in a sandbox iframe that's hosted by a hosting frame with an initial size of 0. The sandboxed frame will observe the survey.height events and the survey.closed events to manage the size and appearance of the hosting frame.

See a gist of the implementation

Inject CSS to your studies

For more fine-tuned control of how your study looks, Sprig supports injecting CSS into the survey. Sprig creates a <style/> tag in the <head/> of the iframe and sets the CSS string as the text content.

<script>
    Sprig.styleNonce = 'YOUR_NONCE'; // Optional if your CSP requires nonces
    Sprig('applyStyles','.ul-question {color: red}'); // Example: changes question text color to red
</script>
import Sprig from '@sprig-technologies/sprig-browser';

Sprig.styleNonce = 'YOUR_NONCE'; // Optional if your CSP requires nonces
Sprig.applyStyles('.ul-question {color: red}'); // Example: changes question text color to red
ElementCSS Selector
Container.ul-card__container
Main question title.ul-question
Question subtitle.ul-caption
Progress bar.ul-progress-bar-container

You may call this method at any time (even when a study is already presented) to override the existing CSS rules. Note that calls to this are not additive, you must include all the CSS changes in one call.

Study Event Lifecycle Notifications

Sprig exposes updates throughout the study lifecycle. Here is a sample code block for listening to SDK events in real time:

<script>
    // an example of a simple listener
    const listener = function (e) {
        // does work with data
        console.log(e);
    };

    // to subscribe to Sprig study presented event
    Sprig('addListener', Sprig.UPDATES.SURVEY_PRESENTED, listener);
    // to remove a study presented event listener
    Sprig('removeListener', Sprig.UPDATES.SURVEY_PRESENTED, listener);
</script>
// import the client returned from your Sprig.configure call
import { Sprig } from 'utils/sprig'
//import SprigEvent from the Sprig NPM package
import { SprigEvent } from '@sprig-technologies/sprig-browser';

// an example of a simple listener
const listener = function (e) {
    // does work with data
    console.log(e);
};

// to subscribe to Sprig study presented event
Sprig.addListener(SprigEvent.SurveyPresented, listener);
// to remove a study presented event listener
Sprig.removeListener(SprigEvent.SurveyPresented, listener);

The following supported events are available on Sprig.UPDATES if using the JS snippet, and SprigEvent if using the NPM package:

UPDATES nameSprigEvent nameDataTriggerMin SDK version
QUESTION_ANSWEREDQuestionAnswered{ answeredAt?: number; questionIndex?: number; value: unknown }Question was submitted by visitor. See table below for possible value type per question type.2.24.3
SDK_READYSdkReady{ name: 'sdk.ready' }SDK is loaded and initialized2.10.0
VISITOR_ID_UPDATEDVisitorIDUpdated{ name: 'visitor.id.updated' }Visitor ID is updated2.10.0
SURVEY_DIMENSIONSSurveyDimensions{ name: 'survey.dimensions', contentFrameHeight: int, contentFrameWidth: int }Dimension is changed2.9.0
SURVEY_HEIGHTSurveyHeight{ name: 'survey.height', contentFrameHeight: int }Height is changed1.9.0
SURVEY_WIDTHSurveyWidth{ name: 'survey.width', contentFrameWidth: int }Width is changed2.25.0
SURVEY_WILL_PRESENTSurveyWillPresent{ name: 'survey.will.present', "survey.id": number }Immediately before study will be presented2.15.15
SURVEY_PRESENTEDSurveyPresented{ name: 'survey.presented' }Study is presented (animations have not yet completed)1.9.0
SURVEY_APPEAREDSurveyAppeared{ name: 'survey.appeared' }Study has appeared on screen (animations have completed)2.10.0
SURVEY_WILL_CLOSESurveyWillClose{ name: 'survey.willClose', initiator: 'survey.completed', studyType: 'feedbackButton' | 'inProductSurvey' }Immediately before study frame is dismissed

initiator will be close.click if study is closed, or survey.completed if study is completed
2.5.0
SURVEY_CLOSEDSurveyClosed{ name: 'survey.closed', studyType: 'feedbackButton' | 'inProductSurvey' }Study frame is dismissed (either submitted or closed)1.9.0
FEEDBACK_BUTTON_LOADEDFeedbackButtonLoaded{ name: 'feedback.button.loaded', "survey.id": number}Feedback button was loaded on the page2.7.1
SURVEY_LIFE_CYCLESurveyLifeCycle{ state: 'presented' } or { state: 'dismissed' }Study is presented, or study is closeddeprecated

For the event when a question is answered, it will return the value the user submitted. See below for each question type and its possible value. There are mainly two types of value, the user can either submit an answer or skip it. Please be aware of all possible outcome of survey responses.

Question TypeInputValue(s)
Text/URLClickedvalue: undefined
Text/URLSkippedvalue: {skipped: true}
Consent/Legal FormSubmittedvalue: {submitted: boolean, name?: string}
Consent/Legal FormSkippedvalue: null
Rating ScaleSubmittedvalue: number
Rating ScaleSkippedvalue: null
Open TextSubmittedvalue: string
Open TextSkippedvalue: ''
Multiple-Choice Single ChoiceSubmittedvalue: { [optionId]: string }
Multiple-Choice Single ChoiceSkippedvalue: {}
Multiple-Choice Multiple ChoiceSubmittedvalue: { [optionId1]: boolean, [optionId2]: boolean, ... }
Multiple-Choice Multiple ChoiceSkippedvalue: { [optionId1]: boolean, [optionId2]: boolean, ... } (same as submitted but all false value)
NPSSubmittedvalue: number
NPSSkippedvalue: null
Voice and VideoSubmittedvalue: { mediaRecordingUid: string }
Voice and VideoSkippedvalue: null
Recorded TaskSubmittedvalue: {taskStatus: “completed”}
Recorded TaskGiven upvalue: {taskStatus: “given.up”}
Recorded TaskSkippedvalue: {taskStatus: “abandoned”}