Link up
This guide covers a hypothetical scenario where you have a hybrid app running on Android and iOS. It explains how to bridge the gap between HTML views and native views so that you can log events in your HTML views and send them to your app.
To apply this method, SDK installation and integration must be done first.
JavaScript interface
Both Android and iOS have native JavaScript interfaces that allow you to call native code from web views.
Android: JavascriptInterface
iOS: JavaScriptCore
Implementation consists of the following steps:
HTML code for Webview or webpage
Native code implementation for Webview
Android
HTML code for Android
Add the following HTML code to your Webview or web page.
<h1>Logging Event From Web View</h1>
<div id="main">
 <button id="logSignUpEvent" onclick="logSignUPEvent()"> SignUp </button>
</div>
<script type="text/javascript">
 function logLoginEvent(){
 var eventName = "df_sign_up"
 var eventProperty = {'df_sign_channel': 'Facebook'};
 window.customJsBridge.logEvent(eventName, JSON.stringify(eventProperty));
}
</script>WebActivity class
Create a web activity class using the following code.
myWebview.getSettings().setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(new MainJsInterface(), "customJsBridge");
myWebView.loadUrl("https://yourwebsite.com");webView.settings.apply {
  this.javaScriptEnabled = true
}
myWebView.addJavascriptInterface(MainJsInterface(), "customJsBridge")
myWebView.loadUrl("https://yourwebsite.com")Javascript interface class
Create a MainJsInterface class that will implement invoke() with JavascriptInterface.
public class MainJsInterface {
    @JavascriptInterface
    public void logEvent(String eventName, String eventProperty){
        JSONObject eventPropertyJsonObject = null;
        if(eventProperty != null){
            try {
                eventPropertyJsonObject = new JSONObject(eventProperty);
                } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        Dfinery.getInstance().logEvent(eventName, eventPropertyJsonObject);
    }
}class MainJsInterface {
    @JavascriptInterface
    fun logEvent(eventName: String?, eventProperty: String?) {
        var eventPropertyJsonObject: JSONObject? = null
        if (eventProperty != null) {
            try {
                eventPropertyJsonObject = JSONObject(eventProperty)
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }
        Dfinery.getInstance().logEvent(eventName!!, eventPropertyJsonObject)
    }
}iOS
HTML code for iOS
Add the following HTML code to your Webview or web page.
<h1>Logging Event From Web View</h1>
<div id="main">
 <button id="logSignUpEvent" onclick="logSignUPEvent()"> SignUp </button>
</div>
<script type="text/javascript">
 function logLoginEvent(){
 var eventName = "df_sign_up"
 var eventProperty = {'df_sign_channel': 'Facebook'};
 var message = {
    'eventName' : eventName,
    'eventProperty' : eventProperty
 };
 webkit.messageHandlers.customJsBridge.postMessage(message);
}
</script>WKWebView Settings
Please connect the messageHandler of the WKWebView object as follows and load the webview.
import UIKit
import WebKit
import DfinerySDK
class WebView: UIViewController, WKScriptMessageHandler {
    var webView: WKWebView!
    
    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        view = webView
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // messageHandler connection
        webView.configuration.userContentController.add(self, name: "customJsBridge")
        let myURL = URL(string:"https://www.YOUR_WEBSITE.com")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }
    // WKScriptMessageHandler Protocol implementation
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name == "customJsBridge", let messageBody = message.body as? [String: Any] {
            if let eventName = messageBody["eventName"] as? String,
               let eventProperty = messageBody["eventProperty"] as? [String: Any] {
                // Dfinery SDK event call
                Dfinery.shared().logEvent(name: eventName, properties: property)
            }
        }
    }
}// WebView.h
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
#import <DfinerySDK/DfinerySDK.h>
@interface WebView : UIViewController <WKScriptMessageHandler>
@property (nonatomic, strong) WKWebView *webView;
@end
@implementation WebView
// WebView.m
#import "WebView.h"
@implementation WebView
- (void)loadView {
    WKWebViewConfiguration *webConfiguration = [[WKWebViewConfiguration alloc] init];
    self.webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:webConfiguration];
    self.view = self.webView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // messageHandler connection
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"customJsBridge"];
    
    NSURL *myURL = [NSURL URLWithString:@"https://www.YOUR_WEBSITE.com"];
    if (myURL) {
        NSURLRequest *myRequest = [NSURLRequest requestWithURL:myURL];
        [self.webView loadRequest:myRequest];
    }
}
// WKScriptMessageHandler Protocol implementation
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"customJsBridge"]) {
        if ([message.body isKindOfClass:[NSDictionary class]]) {
            NSDictionary *messageBody = (NSDictionary *)message.body;
            
            NSString *eventName = messageBody[@"eventName"];
            NSDictionary *eventProperty = messageBody[@"eventProperty"];
            
            if (eventName && [eventProperty isKindOfClass:[NSDictionary class]]) {
                // Dfinery SDK event call
                [[Dfinery shared] logEvent:eventName withProperties:eventProperty];
            }
        }
    }
}
@end
Learn more
Enter date and time format properties
Date and time formats yyyy-MM-dd'T'HH:mm:ss.SSS'Z'must be entered as strings in the format.
let today = new Date().toISOString();
let eventName = "df_sign_up"
let eventProperty = {
    'custom_property': today
};
window.customJsBridge.logEvent(eventName, JSON.stringify(eventProperty));let today = new Date().toISOString();
var eventName = "df_sign_up"
let eventProperty = {
    'custom_property': today
};
var message = {
    'eventName' : eventName,
    'eventProperty' : eventProperty
 };
webkit.messageHandlers.customJsBridge.postMessage(message);Set user identification information
DFINERY Android SDK accepts user identification information as an Enum. To enter user identification information in HTML, it is recommended to input the value of the user identification information constant, convert the string to an Enum in the JavaScript interface, and then call it.
Javascript
window.customJsBridge.setIdentity('external_id', 'sampleUser');public class MainJsInterface {
    @JavascriptInterface
    public void setIdentity(String key, String value){
        DFIdentity identity = DFIdentity.get(key);
        DfineryProperties.setIdentity(identity, value);
    }
}class MainJsInterface {
    @JavascriptInterface
    fun setIdentity(key: String?, value: String?) {
        val identity: DFIdentity = DFIdentity.get(key)
        DfineryProperties.setIdentity(identity, value)
    }
}Last updated