Link Search Menu Expand Document

Snapyr SDK for JavaScript

The Snapyr SDK for JavaScript makes it simple to connect your web application to the Snapyr platform.

SDK-supported Browser Versions

  • Safari >= 13.4
  • Edge >= 80
  • Firefox >= 79
  • Chrome >= 80
  • Opera >= 67

Using the JavaScript SDK

Set up the library

To integrate the SDK, place the following code snippet in the <head> section of your website:

<script>
  snapyr = window.snapyr = [];
  for (
    var methods = [
        "load",
        "page",
        "track",
        "identify",
        "alias",
        "group",
        "ready",
        "reset",
        "getAnonymousId",
        "setAnonymousId",
        "trackInAppMessageImpression",
        "trackInAppMessageClick",
        "trackInAppMessageDismiss",
      ],
      i = 0;
    i < methods.length;
    i++
  ) {
    var method = methods[i];
    snapyr[method] = (function (n) {
      return function () {
        snapyr.push([n].concat(Array.prototype.slice.call(arguments)));
      };
    })(method);
  }

  snapyr.load(
    "YOUR_WRITE_KEY_HERE",
    "https://engine.snapyr.com"
    // { ...see options docs below }
  );

  snapyr.page();
</script>
<script src="https://sdk.snapyr.com/js/1.0.0/snapyr-sdk.min.js"></script>

Write Key

You’ll need your app’s Snapyr Write Key, which can be found in your Snapyr Workspace Settings.

Main Snapyr SDK Calls

Identify

This lets you setup information about the current user and tie that individual to all actions taken. You can set traits for a specific user and these traits will be tied to every tracking action taken. Note that if you do not call Identify, the Snapyr SDK will generate an AnonymousID for the user.

snapyr.identify("id12345", { email: "name@domain.com" }, () => {
  console.log("in identify call");
});

Snapyr recommends that you make an Identify call once when the user first registers or logs in to his / her account, and then call Identify again if traits are added – for example if the user links her account to Facebook or email and you now have desired data. Snapyr will merge any old traits with new ones and update any traits that use the same key.

Remember, you can replace the properties and traits in the code samples with variables that represent the data you actually collected.

userid String The database ID of the user. If provided, this optional argument will be sent to destinations as the user ID instead of an anonymous ID
traits Dictionary,optional Contains the traits or properties associated with a userid such as email, address, etc.
callback This function gets executed after successful execution of the identify call

Track

The Track call is at the heart of Snapyr and allows you to keep track of events or actions your users perform. Every event can also have associated properties.

snapyr.track(
  "purchase", // the event name
  {
    // event properties
    revenue: 30,
    currency: "USD",
    time: "2022-07-05T14:30:00.000Z",
    // property types are intelligently parsed by the snapyr engine
    // as either Text, Boolean, Number, or Date
  },
  () => {
    console.log("in track call");
  }
);

You might also want to track events that indicate key spots hit such as Registered, Logged In, Complete Tutorial, or Purchased an Item.

event String A string that captures the name of the event that is being tracked
properties Dictionary,optional An optional dictionary that tracks the properties of the event
callback This function gets executed after successful execution of the track call

Page

The Page method lets you record whenever a user opens up a new page of your web site / app, along with optional extra information about the page being viewed.

snapyr.page(category, name, properties, callback);

Example:

snapyr.page("iap", "gold store", { gold_value: 30 }, () => {
  console.log("in page call");
});

The page call has the following fields:

name String,optional A name for the screen. Optional if category is provided.
category String,optional A category for the screen. Optional if name is provided.
properties Object,optional A dictionary of properties for this screen. Note: url, title, referrer and path are collected automatically.
callback This function gets executed after successful execution of the track call

AnonymousID and Reset

The Reset method can clear the SDK’s internal data for the current user, such as user traits. This is useful if a user logs out so that multiple users with different identities can be tracked properly.

Note that when you call Reset, Snapyr will assign the new user an AnonymousID until a new id is explicitly set via the Identify method.

The SDK generates a unique Anonymous ID and stores it in a cookie named rl_anonymous_id and attaches to every subsequent event. This allows users to be identified across the domain or sub-domains.

snapyr.reset();

Opt Out

If you need to opt out of tracking for privacy reasons, then set a trait called optOutOfSession with a value of true to the identify or track call. The call will be opted out of the current session or a new session will not be created, if there isn’t already any active session.

Debug Logging

If you want to dive deeper into the Snapyr SDK and all of the events it is sending, you can enable logging.

snapyr.debug(true);

We recommend setting debug to false for the production build of your app or game.

In-App Messaging

The Snapyr SDK includes functionality that can respond to actions sent from the Snapyr Engine — allowing marketers to publish content directly to users while they are using the app.

For example, a marketer creates a campaign that publishes an In-App Message whenever a certain event is fired:

Now, if an "appopen" event is fired by that user from anywhere, the Snapyr SDK will receive that action and automatically display the content (in the case of an In-App Overlay) or send the payload to the actionHandler (in the case of a Custom Payload).

In-App Overlays vs Custom Payloads

The Snapyr SDK provides an out-of-the-box In-App Overlay feature that receives a marketer-defined HTML Creative and automatically displays it to the user in the app. No extra configuration is necessary for this to work other than the basic SDK setup and a properly constructed Snapyr Campaign.

If for some reason this stock implementation doesn’t fit your business’s needs, alternatively, a Custom Payload can be configured instead of the In-App Overlay. When Custom Payload Creatives are sent as Actions, the Action is not handled by the Snapyr SDK at all. Instead, the Action is delivered to a developer-defined actionHandler, where your own custom code can be written to handle the content whenever and however you prefer.

The actionHandler is defined in the options argument of the snapyr.load function:

// define the callbacks directly on the load method like:
snapyr.load(YOUR_WRITE_KEY, "https://engine.snapyr.com", {
  actionHandler(action) {
    console.log("action received!:", JSON.stringify(action, null, 2));
    // do something with the action
  },
});

Custom Payloads can contain either JSON or HTML, both of which support merge tags. The shape of an In-App Action is:

interface InAppAction {
  actionToken: string;
  userId: string;
  timestamp: string; // iso date string
  actionType: "custom" | "overlay"; // 'custom' will be sent to action handler, 'overlay' will be handled exclusively by sdk
  content: {
    payloadType: "json" | "html";
    payload: string; // either '<html />' or '{ "user defined": "json object or array", "will be": "stringified" }'
  };
}

Tracking Analytics for In-App Messages

Snapyr lets you track user interaction metrics for your in-app messages to enable your team to measure the performance of your campaigns.

Automatic tracking with In-App Overlay messages

If you use an In-App Overlay message, the Snapyr SDK automatically manages the entire message lifecycle - displaying, closing, and recording metrics. Metrics will be tracked as follows:

  • Impression - this metric is recorded as soon as the In-App Overlay is displayed on the user’s screen.
  • Click - this metric is recorded any time a user clicks or taps one of the links or buttons within the overlay. If the click is on a link, the URL will be tracked as an additional piece of data.
  • Dismiss - if the user closes the overlay without clicking on something inside of it first, it’s recorded as a dismiss. If a user clicks a link, then later closes the overlay, it is not tracked as a dismiss.

Manual tracking for custom messages

For custom in-app messages, your code has full control over how, and whether, it displays content to the user. The Snapyr SDK can’t measure analytics automatically for custom code. Instead it provides a set of tracking functions that you can call from your code at the appropriate time. These calls cover the same set of metrics as those of In-App Overlay messages.

Every incoming in-app message includes an actionToken parameter, which is a unique string for the message. You’ll need to pass this value back to the tracking calls, which allows Snapyr to automatically connect metrics back to the source message and campaign.

Impression: trackInAppMessageImpression(actionToken: string, properties?: Record<string, any>) Call immediately after you've presented a message to the user.
Click: trackInAppMessageClick(actionToken: string, properties?: Record<string, any>) Call when a user clicks on, or otherwise has a positive engagement with, the message. The second parameter, properties, is optional. If you have additional data to record for this click, you can include it here as a key-value object. For example, you might include the url for a link that was clicked.
Dismiss: trackInAppMessageDismiss(actionToken: string, properties?: Record<string, any>) Call if your user dismisses the message without first performing any clicks or other positive engagement.

Example usage (pseudocode):

window.snapyr.load('WRITE_KEY', 'https://engine.snapyr.com', {
  async actionHandler(action) {
    // actionToken is required to properly identify these behavior events with the corresponding In-App Message
    const { actionToken } = action

    if (action.content.payloadType === 'html') {
      // action.content.payload contains the HTML
      showMyCustomHTMLNotification(action.content.payload)
        .on('open', () => window.snapyr.trackInAppMessageImpression(actionToken))
        // using optional second argument to pass custom event properties to the click event
        .on('click', (details) => window.snapyr.trackInAppMessageClick(actionToken, { buttonChosen: details.button }))
        .on('close', () => window.snapyr.trackInAppMessageDismiss(actionToken))
    }

    if (action.content.payloadType === 'json') {
      // action.content.payload contains the custom JSON data
      await registerJSONData(action.content.payload)
      window.snapyr.trackInAppMessageImpression(actionToken)

      addListener('myParticularEvent', (event) => {
        // let's assume this means the JSON data received a special user response (like a "click")
        window.snapyr.trackInAppMessageClick(actionToken, { activityId: event.id }))
      })
    }
  }
})

Synchronous vs Asynchronous Actions

What follows here includes implementation details of the Snapyr SDK, which may be subject to change in the future, but depending on how you integrate, some of this knowledge may be useful or at least insightful.

In the example Campaign above, that logic will execute “synchronously” with respect to the http request that carries the "appopen" event to the Snapyr Engine. When that event is received, the entire Campaign will execute, and the In-App Action will be rendered and subsequently sent back in the response from the request. The implication of this, of course, is that the Snapyr SDK can immediately respond to that action. Easy peasy. However, some Campaigns might include a “Wait” block before the “Publish” block, which means the request will return before the entire campaign can execute. In this case, the In-App Action will be published “asynchronously,” and in order for the Snapyr SDK to respond to it, a polling mechanism runs every 30 seconds, querying for any outstanding In-App Actions. Once an asynchronous Action is received, it is handled the same as all other Actions: In-App Overlays are automatically displayed, and Custom Payloads are sent to the actionHandler.

The actionPollInterval (in milliseconds) can be changed in the options argument of the snapyr.load function:

// define the callbacks directly on the load method like:
snapyr.load(YOUR_WRITE_KEY, "https://engine.snapyr.com", {
  actionHandler(action) {
    console.log("action received!: " + JSON.stringify(action));
    // do something with the action
  },
  actionPollInterval: 60000,
});

The actionPollInterval has a floor of 10000 (10 seconds), and setting it to 0 will disable polling entirely, thus preventing asynchronous Actions from being received without triggering an event.

NB: every time an event is sent, any pending asynchronous Actions are sent back in the response, whether that particular event triggered a Campaign or not.

Enjoy!