In-App Events from a Native Web View

Introduction

Sometimes, apps use web views containing HTML content. It is possible to call AppsFlyer's APIs for tracking events from Javascript code in the web view.

The following code shows an example for tracking an In-App Event:

HTML Code (for both Android WebView and iOS UIWebview)

function trackEvent(eventName,eventValue){
         var iframe = document.createElement("IFRAME");
         iframe.setAttribute("src", "af-event://inappevent?eventName="+eventName+"&eventValue="+eventValue);
         document.documentElement.appendChild(iframe);
         iframe.parentNode.removeChild(iframe);
         iframe = null;
}

The web view must call the native app which, in turn, calls AppsFlyer's SDK.

 Example

button.onclick = function(event) {
  var eventName = "af_purchase";
  var eventValue = "{\"af_revenue\":6.72 ,\"af_content_type\":\"wallets\", \"af_content_id\":\"15854\"}";
  trackEvent(eventName, eventValue);
};

 

Android Implementation iOS Implementation

Android WebView uses a WebViewClient that receives notification from the web view.  In the shouldOverrideUrlLoading, you can handle events coming from the WebView as follows:

mWebView.setWebViewClient(
                new WebViewClient() {
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        if (url.startsWith("af-event://"))  {
                            String[] urlParts = url.split("\\?");
                            if (urlParts.length > 1) {
                                String query = urlParts[1];
                                String eventName = null;
                                HashMap<String, Object> eventValue = new HashMap<>();

                                for (String param : query.split("&")) {
                                    String[] pair = param.split("=");
                                    String key = pair[0];
                                    if (pair.length > 1) {
                                        if ("eventName".equals(key)){
                                            eventName = pair[1];
                                        } else if ("eventValue".equals(key)){
                                            eventValue.put(pair[0], pair[1]);
                                        }
                                    }
                                }
                                AppsFlyerLib.getInstance().trackEvent(CurrentActivity.this,eventName,eventValue);
                            }
                            return false;
                        }
                        return true;
                    }});
Was this article helpful?
0 out of 2 found this helpful