Getting Started

mParticle’s web SDK is designed to flexibly support all modern browsers as well as connected TVs and other Javascript-based client-side environments.

Create an Input

To send data from your web app to your mParticle workspace input, navigate to Setup > Inputs and select the Web platform. The web SDK only needs the API Key (not the API secret), which you’ll replace in the snippet below. Reference the guide section for information on creating inputs.

Add the SDK Snippet

The following snippet should be included on every page of your web app. Ideally, it should be placed within the <head> tag or otherwise be loaded as soon as possible on each page. The mParticle web SDK is lightweight (under 30KB depending on your configuration) and distributed globally via a CDN.

<script type="text/javascript">
  window.mParticle = {
    config: {
      isDevelopmentMode: true //switch to false (or remove) for production
    }
  };

  (
    function(t){window.mParticle=window.mParticle||{EventType:{Unknown:0,Navigation:1,Location:2,Search:3,Transaction:4,UserContent:5,UserPreference:6,Social:7,Other:8}};window.mParticle.eCommerce={Cart:{}};window.mParticle.Identity={};window.mParticle.config=window.mParticle.config||{};window.mParticle.config.rq=[];window.mParticle.ready=function(t){window.mParticle.config.rq.push(t)};function e(e,o){return function(){if(o){e=o+"."+e}var t=Array.prototype.slice.call(arguments);t.unshift(e);window.mParticle.config.rq.push(t)}}var o=["endSession","logError","logEvent","logForm","logLink","logPageView","setSessionAttribute","setAppName","setAppVersion","setOptOut","setPosition","startNewSession","startTrackingLocation","stopTrackingLocation"];var n=["setCurrencyCode","logCheckout"];var i=["identify","login","logout","modify"];o.forEach(function(t){window.mParticle[t]=e(t)});n.forEach(function(t){window.mParticle.eCommerce[t]=e(t,"eCommerce")});i.forEach(function(t){window.mParticle.Identity[t]=e(t,"Identity")});var r=document.createElement("script");r.type="text/javascript";r.async=true;r.src=("https:"==document.location.protocol?"https://jssdkcdns":"http://jssdkcdn")+".mparticle.com/js/v2/"+t+"/mparticle.js";var c=document.getElementsByTagName("script")[0];c.parentNode.insertBefore(r,c);}
  )("REPLACE WITH API KEY");
</script>

Verify connection

As soon as you load a page with this snippet, you should be able to see data arriving in your live stream:

If you don’t see data in the live stream after loading the page:

  • Verify that the API key in your snippet correctly matches your workspace’s web input
  • Verify that the window.mParticle.config object contains isDevelopmentMode: true
  • Use your browser’s developer tools window to verify that web requests to all *.mparticle.com domains are succeeding

Listen for SDK Initialization

The web SDK loads asynchronously and is therefore not immediately available for use. However, this snippet creates stubbed versions of several mParticle APIs such that your function invocations are queued until the SDK loads. The following APIs are stubbed for you and will be placed on a function queue when invoked after the snippet but prior to when the SDK loads:

You may also add any function to a generic queue via the mParticle.ready() helper method and it will be invoked once the SDK loads:

window.mParticle.ready(
  function() { 
    console.log('mParticle has loaded!'); 
     // !! Note: do not attempt to access the user object at this point
     // !! var user = window.mParticle.Identity.getCurrentUser();
     // !! Instead, access the user object via the mParticle.config.identityCallback option
  }
);

SDK Configuration

The web SDK evaluates the window.mParticle.config object for configuration upon initialization. The complete list of configuration options is as follows and several detailed examples are below.

Setting Type Default Description
isDevelopmentMode Boolean false Development mode - All data sent through mParticle is marked as development or production. Set this to true in your test and QA environments
identifyRequest Object See description IDSync Request - a request object containing the desired initial IDSync identify request. If excluded, the SDK will use the identities of the most recent/previous user if present.
identityCallback Function object null IDSync callback - a callback function to run on completion of the initial identify request
sessionTimeout Number 30 Session timeout - an inactivity timeout in minutes after which a session will expire
appVersion String null Web app version - a version string to associated with your web app
useCookieStorage Boolean false Flag to set the persistence storage to cookies, instead of local storage (default).
useNativeSdk Boolean false Flag to allow the web SDK to bind to a native iOS or Android webview, in an app containing the mParticle iOS/Android SDKs
maxProducts Number 20 Maximum products - Maximum number of products allowed in the cart, any additional items will not be added.
customFlags Object null Custom flags - several integrations require custom flags on initialization.

Identify Request

The web SDK does the following on every page load:

  • Detects if there is an active session in the current or any other browser tab
  • If an active session is not found, the SDK constructs an IDSync request containing the most recent user identities from the previous browser session. You can manually specify the IDSync request via the identifyRequest property of your mParticle.config object.
  • If an active session is found, then no IDSync HTTP request is performed
  • Regardless of whether an IDSync HTTP request is performed, the SDK will invoke the IDSync callback function described below.

A common use-case is to access the mParticle user object immediately on page load. The best way to do this is to specify a function as the identityCallback property of your mParticle.config object:

window.mParticle = {
  config: {
    identifyRequest: {
      userIdentities: {
          email:      'email@example.com',
          customerid: '123456'    
      }
    },
    identityCallback: function(result) {
        //This is the quickest way to acquire a reference to the user object
        //this callback is invoked on every page load
        if (result.getUser()) {
            result.getUser().setUserAttribute('foo', 'bar');
        }
    }
  }
};

See the IDSync documentation for more information on building a complete IDSync request.

Environment

All data sent into an mParticle input must be marked as either “development” or “production”. Whereas several mParticle SDKs attempt to auto-detect the environment, the web SDK always defaults to production.

You can override the environment in your mParticle.config object:

window.mParticle = {
  config: {
    isDevelopmentMode: true //switch to false (or remove) for production
  }
};

Was this page helpful?