Upsight logo Back to top

Web

Overview

Upsight Web SDK


Upsight is the most comprehensive analytics and marketing platform for web and mobile apps. We are building a business engine to help our customers better understand user behavior, decide what it means, and act to impact key goals.

If you have any questions, contact Upsight Support. We also recommend reviewing our Optimization Guides to learn the best practices and get the most out of your Upsight integration.

Getting Started

Basic Integration


To get started with Upsight's Web SDK simply paste the following code snippet.

<script>
    !function(a,b,c,d,e){a.upsight=a.upsight||function(){for(var a=["createBillboard","extendSession","getAllAttributes","getAttribute",
    "getBillboard","getLatestSessionInfo","getSenderId","init","isContentReady","recordMilestone","removeAllAttributes","removeAttribute",
    "setAttribute","startNewSession","trackCustomEvent","trackMonetizationPriceQuantity","trackMonetizationTotal"],
    b={q:[]},c=0,d=a.length;c<d;c++){var e=a[c];b[e]=function(a){return function(){b.q.push([a,(new Date).getTime(),arguments])}}(e)}
    return b}();var f=b.createElement("script"),g=b.getElementsByTagName("script")[0];f.src="https://js.upsight-api.com/upsight-sdk.min.js",
    f.async=!0,g.parentNode.insertBefore(f,g)}(window,document);
</script>

The code snippet will add a global 'upsight' instance to the 'window' object and creates a queue as a placeholder for the SDK until the SDK is finally loaded. All methods that were previously enqueued will execute immediately when the SDK is ready. In order to work with the 'upsight' instance, it must first be initialized with your application token.

upsight.init('YOUR_APP_TOKEN');

At this point your application should be setup to send messages to Upsight. If you open the Upsight realtime page and then your application, you should see events appear. If there is not a current session in progress then an 'upsight.session.start' event is automatically sent once you call init. The event includes a 'sid' which is generated to uniquely identify the browser and persisted on the client to be used for subsequent sessions. The value of this id can be retrieved using 'getSenderId'.

upsight.getSenderId(function(senderId) {
  console.log(senderId);  // Logs the sender ID
});

Note All standard metrics are based on this identifier and are thus based on the browser being used to access the application and not on the specific user who is logged in.

Getting Started

Debugging


To see whether or not Upsight is successfully integrated after you added in your App Token, you can look at our Real Time dashboard or your browser's network tab.
NoteIt takes an hour for the real time monitor to first start showing data from a newly created application.

Since the dashboard takes time to process data, to track these messages in real time and ensure proper integration go to Real Time. Go to Real Time > Select App > Click on Filter.

Integration Center

After just calling upsight.init, you should see session events on the realtime page.

  • Opening the page for the first time will generate an "upsight.session.start" message.

Every message includes an sid, which is generated to uniquely identify the browser and persisted on the client to be used for subsequent sessions. The value of this id can be retrieved using upsight.getSenderId. Note that all standard metrics are based on this identifier and are thus based on the browser being used to access the application and not on the specific user who is logged in.

You can also turn on logging for the Upsight SDK when calling upsight.init and passing in debug, info, warn, or exception to logLevel as part of the optional parameters as indicated the init method reference:

upsight.init('YOUR_APP_TOKEN', {
    logLevel: "debug"
});

Getting Started

Custom Events


Once you have initialized the SDK, you can track an event just by setting the event name and properties as indicated in the code example below:

var myData =  { 
    item_value : 100
    item_name: "name"
}

upsight.trackCustomEvent("event_name", myData);

Set properties to null or simply call upsight.trackCustomEvent("event_name") if there are no properties you want tracked. Otherwise, create a JSON object representing the event properties you wish to track. Examples include a soft currency value, and item type. Additionally, for custom events periods can be used in the event name to create event hierarchy such as category.subcategory.my_event_name.

Getting Started

Tracking Events


Tracking Events

To track additional events from your application you can call 'trackCustomEvent' anytime something interesting happens.

upsight.trackCustomEvent('my.event', {
  eventAttributeA: 'premium',
  eventAttributeB: 'used_coupon'
});

The supported tracking methods are:

  • trackCustomEvent()
  • trackMonetizationTotal()
  • trackMonetizationPriceQuantity()

Tracking User Attributes

You can also tie particular attributes to your application's current user by calling setAttribute. These attributes will automatically be sent along with every tracking event. Note that you should use one of the remove methods to clear these attributes on logout so that they aren't inadvertently sent for another user later on. The supported user attribute methods are:

  • getAllAttributes()
  • getAttribute()
  • removeAllAttributes()
  • removeAttribute()
  • setAttribute()

Methods Requiring Callbacks

Because the SDK executes its methods asynchronously by default, any method that returns a value requires a callback method. The provided callback method will be invoked with the return value, which the developer can then set their own variable with that return value.

Example:

upsight.setAttribute('my_attribute', 'some value');

upsight.getAttribute('my_attribute', function(attr) {
  console.log(attr); // Logs 'some value'
});

The following methods require a callback method to be passed as an argument to get the return value:

  • createBillboard()
  • getAttribute()
  • getBillboard()
  • getLatestSessionInfo()
  • getSenderId()
  • isContentReady()

Session Control

By default if a tracking event occurs and the browser has not sent an event within the last 30 minutes then a new session is considered to have begun. The length of this interval can be configured when calling 'init'. In addition the SDK provides an 'extendSession' method which tells it to wait an additional interval before beginning a new session as well as 'startNewSession' which will immediately trigger a new session start.

User Attributes

User Attributes


Because the SDK executes its methods asynchronously by default, any method that returns a value requires a callback method. The provided callback method will be invoked with the return value.

Example:

upsight.getAttribute('my_attribute', function(attr) {
  console.log(attr); // Logs 'some value'
});

This returns the current value of the user attribute. You can continue to update the attribute by calling setAttribute as shown below:

upsight.setAttribute('my_attribute', 'some value');

Additionally, you can get all attributes as a JSON object with getAllAttributes, remove a single attribute with removeAttribute and remove all attributes with removeAllAttributes.

Once you have set User Attributes in your code, add it as a Custom Attribute in your dashboard under Settings > Applications > App name > Edit app > Custom Attributes. This will allow you to segment and create analytics using your User Attributes.

When creating, you may select string or a list of strings. string attributes allow you do store and match on a single item, for example, Team, City or Gender. A list of strings allows you to store a list of items and then create segments based on whether or not that list contains, or does not contain, specific items. This could be used to store a list of purchases, subscriptions, or other items, and is a more effective way to match against set which may contain lots of different items than creating individual boolean attributes, one for each item in the list. A list of strings should still be defined with the string type in your Manifest and should be composed by comma separating the items into a single string when you set the value.

Custom Attributes

Once you're at the user attribute page, to add an attribute, follow these steps:

  1. Click "Add Custom Attribute" to add a new custom attribute
  2. Choose the name, type, and default value of each attribute

Marketing

Marketing Integration


Marketing

The Upsight SDK uses a concept of 'Billboards' and 'Milestones' for delivering content to mobile and web devices.

Note For web devices, the marketing campaign type you must choose is "Native Messaging". These campaigns allow you to add values for several different data types, including text, images, and colors. Once the campaign values have been sent down to your app, you can use them to assemble your final creative.

Native Messaging

Milestones are Upsight's way of triggering requests to retrieve content from our API. When a Milestone is triggered, the API will determine whether content is available for a particular Milestone. If content is available, the API will deliver the specified content to the end user's device where it will be stored by the SDK. Billboards, on the other hand, are Upsight's mechanism for displaying content delivered to the SDK. Milestones and Billboards are decoupled and can each be created without any dependency on the existence of the other object. However, in order for content to be successfully delivered, instances of Milestone(s) and Billboard(s) with matching scopes must be present. For example, if an event in your application triggers a Milestone with scope: "foo", the SDK will check to see if a Billboard instance with the identical scope: "foo" exists. If a match is found, the SDK will attach the content from the Milestone to the matched Billboard. If a match is not found, the content from the Milestone will be stored and placed in a queue until a Billboard with an identical scope is intialized.

To provide more context as to how content is delivered using Upsight, let's go ahead and create a billboard:

var handlers = {
  onData: function(content) {},
  onDetach: function() {}
};
upsight.createBillboard('foo', handlers, function(billboard) {
  console.log(billboard); // Logs the create billboard instance
});

The code snippet above creates and returns a new Billboard instance with the scope "foo" to the provided callback method. The 'handlers' object passed as the second argument manages any actions to be taken once content is available, which is explained below. Additionally, the 'handlers' object is responsible for doing anything when the Billboard instance is destroyed.

Now that we have created a Billboard instance with scope: "foo", we are ready to attach content to our initialized Billboard by recording a milestone with a matching scope value.

upsight.recordMilestone('foo');

Since there is a matching Billboard instance with the scope: "foo", the received content for the Milestone automatically attaches to the Billboard instance and the onData method will be executed. A 'content' object is passed as an argument to the 'onData' method which the developer can interact with readily. See Content for more information about its various methods.

var handlers = {
  onData: function(content) {
    var data = content.getJSON();
  },
  onDetach: function() {
    // do something
  }
}
upsight.createBillboard('foo', handlers);
upsight.recordMilestone('foo');

When the 'onData' method finishes execution, the Billboard instance's default action will be to destroy itself. However, if the developer saved a reference to the 'content' object before the billboard is destroyed, the developer would still have access to the 'getJSON' method of the 'content' object, but will be unable to execute any of the event recording methods.

var myContent;
var handlers = {
  onData: function(content) {
    myContent = content;
  }
};
upsight.createBillboard('foo', handlers, function(billboard) {
  upsight.recordMilestone('foo', undefined, function() {
    // The billboard will have been destroyed by this point because the
    // content was successfully attached to the Billboard.

    var data = myContent.getJSON(); // Still returns data properly
    myContent.recordDismissEvent(); // Does nothing
  });
});

In order to override the default behavior and prevent a billboard from automatically destroying itself, the developer must return the 'KEEP_ALIVE' flag provided by the 'content' in the 'onData' method.

var myContent;
var handlers = {
  onData: function(content) {
    var data = content.getJSON();
    return content.KEEP_ALIVE;
  },
  onDetach: function() {
    // do something
  }
};
upsight.createBillboard('foo', handlers, function(billboard) {
  upsight.recordMilestone('foo', undefined, function() {
    // Since the `KEEP_ALIVE` flag was returned in the `onData` method of the
    // handler, the event recording method will work properly.

    var data = myContent.getJSON(); // Still returns data properly
    myContent.recordDismissEvent(); // records a 'content_dismissed' event
    myContent.destroy(); // dismisses the content
  });
});

Note A new Billboard cannot be created using an existing Billboard scope. The developer must destroy the existing Billboard for a specific scope before trying to create a new Billboard with that same scope. When a billboard is destroyed, the 'onDetach' method will be invoked. Within the 'onDetach' method, a developer can perform any clean up after displaying the delivered content. To destroy the Billboard instance manually, simply invoke the 'destroy' method from the instance.

var handlers = {
  onData: function(content) {
    var data = content.getJSON();
    return content.KEEP_ALIVE;
  },
  onDetach: function() {
    // do something
  }
};

upsight.createBillboard('foo', handlers, function(billboard) {
  billboard.destroy();
});

It is also important to note that Milestones can be triggered prior to initializing a Billlboard in order to preemptively deliver content to the SDK, so that the desired content is fully downloaded and available before a corresponding Billboard is created. Using this methodology, developers can better optimize their content delivery performance

upsight.recordMilestone('foo', undefined, function() {
  // check to see if there is already a billboard for the scope before trying
  // to create a new one
  upsight.getBillboard('foo', function(billboard) {
    if (!billboard) {
      var handlers = {
        onData: function(content) {
          // do something with the content data
          var data = content.getJSON();

          return upsight.KEEP_ALIVE
        }
      };
      upsight.createBillboard('foo', handlers);
    }
  });
});

Monetization


Monetization

Upsight makes it easy to track and analyze revenue you earn from customers with monetization events. There are two main methods for tracking monetization.

If the item purchased is one that has a quantity, you can leverage the trackMonetizationPriceQuantity method.

If you have a purchase to record that doesn't have a specific resolution or quantity, you can should use the trackMonetizationTotal method instead.

Method Reference

extendSession


Description

Extends the current session by an amount equal to the configured sessionLength value

Example

upsight.extendSession();

Method Reference

getAllAttributes


Description

Gets all of the user attributes

Example

upsight.getAllAttributes(); //=> {'foo': 'bar', 'baz': '23'}

Method Reference

getAttribute


Description

Gets an attribute

Parameters

NameTypeDescription
attrstringThe user attribute to be retrieved.

Example

// All stored attributes are cast as strings
upsight.getAttribute('foo'); // => 'bar'
upsight.getAttribute('baz'); // => '23'

Method Reference

getSenderId


Description

Gets the auto-generated sid

Example

//Asynchronously get the senderId.
upsight.getSenderId(function(senderId) {
  console.log(senderId);  // Logs the sender ID
});

//Synchronously gets the senderId.  This may return null if called quickly after initialization.
upsight.getSenderId();

Method Reference

init


Description

Initialize the SDK

Parameters

NameTypeDescription
tokenstringThe token of the application being instrumented
optionsobjectConfiguration options to override
Properties
NameTypeAttributesDefaultDescription
logLevelstring <optional>
Specifies the minimum logging level outputted by the sdk. Leave blank to disable logging. One of: debug, info, warn, exception
useLocalboolean <optional>
false Specifies whether sdk should use localStorage vs. cookie storage
sessionLengthint <optional>
1800 The duration (in seconds) of a session
appVersionstring <optional>

Example

upsight.init('apptoken9933', {
  useLocal: true
});

Method Reference

removeAllAttributes


Description

Removes all of the user attributes

Example

upsight.removeAllAttributes();

Method Reference

removeAttribute


Description

Removes an attribute

Parameters

NameTypeDescription
attrstringThe user attribute to be removed.

Example

upsight.removeAttribute('bar');

Method Reference

setAttribute


Description

Sets an attribute. All attribute values are cast to strings.

Parameters

NameTypeDescription
attrstring | objectThe user attribute to be set. This param can be a string name to represent the key for the attribute, or an object that contains multiple attributes to be set.
valueobjectAny type of value to be set for the attribute. This param is necessary only if the attr type is a string. If omitted, the value will default to an empty string.

Example

upsight.setAttribute('foo', 'bar');
upsight.setAttribute('baz', 23);
upsight.setAttribute({hi: 'there', good: 'bye'});

Method Reference

startNewSession


Description

Stars a new session

Example

upsight.startNewSession();

Method Reference

trackCustomEvent


Description

Tracks a custom event

Parameters

NameTypeDescription
typestringThe type of the custom event. Value cannot be an empty string
eventDataobjectThe event data to be sent for the custom event.

Example

upsight.trackCustomEvent('joined_group', {
  group_name: 'surfers',
  group_status: 'premium'
});

Method Reference

trackMonetizationPriceQuantity


Description

Tracks a monetization event using price and quantity

Parameters

NameTypeDescription
priceintThe price of the product
quantityintThe quantity of the product
currencystringThe currency
upsightDataobjectThe optional data to be set for monetization
Properties
NameTypeAttributesDescription
productstring<optional>
The name of the product
resolutionstring<optional>
The resolution of the purchase.One of: buy, cancel, fraud, or refund
eventDataobjectAny custom event data to be sent

Example

upsight.trackMonetizationPriceQuantity(20, 3, 'usd', {
  product: 'super-swipe',
  resolution: 'buy'
}, {
  purchased_from: 'cart'

Method Reference

trackMonetizationTotal


Description

Tracks a monetization event using total price

Parameters

NameTypeDescription
totalPriceintThe total price of the product
currencystringThe currency
upsightDataobjectThe optional data to be set for monetization
Properties
NameTypeAttributesDescription
productstring<optional>
The name of the product
resolutionstring<optional>
The resolution of the purchase.One of: buy, cancel, fraud, or refund
eventDataobjectAny custom event data to be sent