Binding Webview to Native App Functions
Handling the interaction between webview programs and the app
Binding Webview clicks to native code

The webview might want to access some native features. Like opening a deeplink, showing the share drawer, etc.
callback
native method should be binded with any webview.The webview will pass
eventJSON
to the callback function.
The webview will call this function in the following ways -
app.callback(eventJSON); //Android
webkit.messageHandlers.callback.postMessage(eventJSON); // iOS
Download Sample Kotlin App from our Github
Download Sample React Native App from our Github
Download Sample Flutter App from our Github
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.util.Log;
import org.json.JSONObject;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView)findViewById(R.id.web_view);
webView.loadUrl("https://app-markk.customerglu.com/program"); // webview url
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebViewJavaScriptInterface(this), "app"); // **IMPORTANT** call it app
}
/*
* JavaScript Interface. Web code can access methods in here
* (as long as they have the @JavascriptInterface annotation)
*/
public class WebViewJavaScriptInterface{
private Context context;
/*
* Need a reference to the context in order to sent a post message
*/
public WebViewJavaScriptInterface(Context context){
this.context = context;
}
/*
* This method can be called from Android. @JavascriptInterface
* required after SDK version 17.
*/
@JavascriptInterface
// **IMPORTANT** call it callback
public void callback(String message){
JSONObject data = new JSONObject(message);
// data has the event information
Log.d(data);
}
}
}
EventJSON
The native callback function should be able to identify the event using
eventName
property present in the JSON.The
data
property contains data relevant to thateventName
.
Check out all possible Webview events here.
Last updated
Was this helpful?