Call java code from ionic typescript (addIavascriptInterface)


I can use addJavascriptInterface in plain Html and js to communicate native java code on android (say for displaying a Toast). But I can’t use this in Ionic and typescript.

here is my mainActivity:

package io.ionic.starter;

import android.content.Context;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.Toast;

import org.apache.cordova.*;

public class MainActivity extends CordovaActivity
public void onCreate(Bundle savedInstanceState)

    // enable Cordova apps to be started in the background
    Bundle extras = getIntent().getExtras();
    if (extras != null && extras.getBoolean("cdvStartInBackground", 
false)) {

    // Set by <content src="index.html" /> in config.xml
    WebView webView = (WebView) appView.getEngine().getView();
    webView.addJavascriptInterface(new WebAppInterface(this), "Android");

 public class WebAppInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
     // Show Toast Message
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();

this is my home.ts in Ionic4:

import { Component } from '@angular/core';
declare var Android:any;
selector: 'app-home',
templateUrl: '',
styleUrls: [''],
export class HomePage {
alert("show alert");
Android.showToast('Toast made by Javascript');

and the html part:

<ion-button (click)="showToast()">show toast</ion-button>

and the error when I debug it is

ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 13, nodeDef: {…}, elDef: {…}, elView: {…}}

someone help me please. i have spent 2 days on getting access from webview to java code without luck!