Native WebViews

In addition to running in a standard web browser environment, the JavaScript SDK is also able to detect when it is running in a native WebView, and communicate with mParticle’s native iOS and Android SDKs, if present.

This allows developers to share the JavaScript tracking code between their web app and the WebView of a mobile app.

How it works

When initialized within a native WebView, the JavaScript SDK operates only as an intermediary, passing data to the native iOS or Android SDK. Data collected in a WebView is sent to mParticle as Android or iOS data. For this reason, you do not need to set up a Web input in the mParticle platform, or provide an API key in the initialization snippet. Instead, you will need to bind the JavaScript SDK to the iOS or Android SDK in your native code.

Because the JavaScript SDK acts as write-only within a WebView, a limited subset of the full SDK functionality is available. All event logging works as normal, and the event data is simply passed to the native SDK to be sent on to mParticle. However, any get methods, such as those used to return the current user, will not work within a WebView. Similarly, any callbacks, such as the optional callbacks for Identity methods, will not work within a WebView.

Setup

There are three different paths for using the JavaScript SDK in a WebView

  • Treat a WebView like a browser - initialize the full JavaScript SDK and send data to the Web input. See our standard [Getting Started] guide for this style of implementation.
  • Hybrid - Use the same snippet to send data to mParticle via the Web input when the code is run in a browser, and via the iOS or Android input when the code is run in a WebView.
  • WebView only - take this approach if you only need to track activity in a mobile WebView and you want the activity attributed to the native app.

Hybrid - Web Browser + WebView

If the same JavaScript will potentially be loaded in a web browser and a native app’s WebView, you will need to set up a Web platform for your app in the mParticle console to acquire the mParticle API key. Add the snippet below, with your Web API key, within the <head> tag of your app.

This setup will cause the SDK to send data via the Web input, when in a browser, and via the native SDK when in a WebView.

<!--Web Browser + `WebView` and Web Browser only -->
<script type="text/javascript">
 (function (apiKey) {
     window.mParticle = window.mParticle || {};
     window.mParticle.eCommerce = { Cart: {} };
     window.mParticle.Identity = {};
     window.mParticle.config = window.mParticle.config || {};
     window.mParticle.config.rq = [];
     window.mParticle.ready = function (f) {
         window.mParticle.config.rq.push(f);
     };

     function a(o,t){return function(){t&&(o=t+"."+o);var e=Array.prototype.slice.call(arguments);e.unshift(o),window.mParticle.config.rq.push(e)}}var x=["endSession","logError","logEvent","logForm","logLink","logPageView","setSessionAttribute","setAppName","setAppVersion","setOptOut","setPosition","startNewSession","startTrackingLocation","stopTrackingLocation"],y=["setCurrencyCode","logCheckout"],z=["login","logout","modify"];x.forEach(function(o){window.mParticle[o]=a(o)}),y.forEach(function(o){window.mParticle.eCommerce[o]=a(o,"eCommerce")}),z.forEach(function(o){window.mParticle.Identity[o]=a(o,"Identity")});

    var mp = document.createElement('script');
    mp.type = 'text/javascript';
    mp.async = true;
    mp.src = ('https:' == document.location.protocol ? 'https://jssdkcdns' : 'http://jssdkcdn') + '.mparticle.com/js/v2/' + apiKey + '/mparticle.js';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(mp, s);
})('YOUR_API_KEY');
</script>
  1. Replace 'YOUR_API_KEY' with the mParticle API key for the Web platform for your app set up in the mParticle platform
  2. When your JavaScript is loaded in a web browser, mParticle will associate event data with your Web API key.
  3. When your JavaScript is loaded in your native app’s WebView, mParticle will associate event data with the respective iOS or Android app’s API key, as long as you bind the JavaScript SDK to the Native SDK.

WebView-only

If your JavaScript will only ever be loaded in native app WebViews, there’s no need to create a web platform for your app. Simply include the JavaScript below without an API key.

<!-- WebView only-->
<script type="text/javascript">
 (function () {
     window.mParticle = window.mParticle || {};
     window.mParticle.config = window.mParticle.config || {};
     window.mParticle.config.rq = [];
     window.mParticle.ready = function (f) {
         window.mParticle.config.rq.push(f);
     };
     var mp = document.createElement('script');
     mp.type = 'text/javascript';
     mp.async = true;
     mp.src = 'https://jssdkcdns.mparticle.com/js/v2/mparticle.js';
     var s = document.getElementsByTagName('script')[0];
     s.parentNode.insertBefore(mp, s);
 });
 </script>
  1. If you are instrumenting a WebView in a native iOS or Android app, you should additionally follow the Getting Started and Initialization steps for either platform, if you haven’t already.
  2. Follow the instructions below to bind the respective native SDK to your WebView.

Bind the JavaScript SDK to the native SDK

Bind the JavaScript SDK to the iOS SDK

The mParticle SDK supports both the WKWebView and UIWebView types.

WKWebView (iOS 8+)

//Step 1: Enables the JavaScript SDK to pass requests from the webview through the iOS SDK
[myWebView evaluateJavaScript:@"mParticle.isIOS = true;" completionHandler:nil];

//Step 2: Use a WKNavigationDelegate to pass all applicable URL requests to mParticle
- (void) webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    if([[MParticle sharedInstance] isMParticleWebViewSdkUrl:navigationAction.request.URL]) {
        [[MParticle sharedInstance] processWebViewLogEvent:navigationAction.request.URL];
    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
}

UIWebView

//Step 1: Enable the JavaScript SDK to pass requests from the webview through the iOS SDK
[[MParticle sharedInstance] initializeWebView:myWebView];

//Step 2: Use a UIWebViewDelegate to pass all applicable URL requests to mParticle
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if([[MParticle sharedInstance] isMParticleWebViewSdkUrl:[request URL]]) {
        [[MParticle sharedInstance] processWebViewLogEvent:[request URL]];
        return  NO;
    } else {
        return YES;
    }
}

In order to use the JavaScript SDK in an iOS App WebView, you must register every UIWebView with mParticle, with the initializeWebView method, as well as pass all applicable UIWebView URL requests through mParticle.

Bind the JavaScript SDK to the Android SDK

WebView wv = (WebView) findViewById(R.id.webview);
MParticle.getInstance().registerWebView(wv);

For every WebView in your Android application, add the mParticle JavaScript interface to its scope.