Communicate between Javascript & WebView

Send data from Javascript to Android code

public class WebViewInterface{
    @JavascriptInterface
    public void methodToBeCalledFromJavascript(){

    }
}
class WebViewInterface {
    @JavascriptInterface
    fun methodToBeCalledFromJavascript() {
      
    }
}
WebViewInterface interface = new WebViewInterface();
webView.addJavascriptInterface(interface, "NativeAndroid");
val interface = WebViewInterface()
webView.addJavascriptInterface(interface, "NativeAndroid")
NativeAndroid.methodToBeCalledFromJavascript();

Send data from Android to Javascript code

String script = "window.updateFromNative(" + eventData + ");";
webView.evaluateJavascript(script, null);
val script = "window.updateFromNative($event);"
webView.evaluateJavascript(script, null)
window.updateFromNative = function (nativeData) {

};


Implement Engagement Starter

Show a Engagement Starter inside the WebView content and link it with the SDK.


interface WebViewDelegate {
		void triggerEngagementStarter();
}
    
public class WebViewInterface {
		private WebViewDelegate webViewDelegate;

    public WebViewInterface(WebViewDelegate webViewDelegate){
        this.webViewDelegate = webViewDelegate;
    }
  
    @JavascriptInterface
    public void triggerEngagementStarter(){
       webViewDelegate.triggerEngagementStarter();
    }
}

public void onPageFinished(WebView view, String url) {
		view.evaluateJavascript("setTimeout(function() { document.querySelector('.vf-conversation-starter_link').onclick = function() {  NativeAndroid.triggerEngagementStarter(); }; }, 5000);", null);
}
WebViewInterface webViewInterface = new WebViewInterface(new WebViewDelegate() {
		@Override
		public void triggerEngagementStarter() {
				float yPosition = (findViewById(R.id.article_comments_container).getY());
				scrollView.smoothScrollTo(0, (int) yPosition);
		}
});

webView.addJavascriptInterface(webViewInterface, "NativeAndroid");