I want to open an activity window in Android WebView passing a String in JavaScript, but I always get this undefined error:
05-18 06:32:02.586 13351-13351/com.vaydesign.tw3 I/chromium﹕ [INFO:CONSOLE(11)] "Uncaught TypeError: Cannot read property 'openActivity' of undefined", source: file:///android_asset/index.html (11)
Part of my MainActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    WebView myWebView = (WebView) findViewById(R.id.webView1);
    myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
    myWebView.setWebViewClient(new WebViewClient());
    myWebView.getSettings().setJavaScriptEnabled(true);
    myWebView.loadUrl("file:///android_asset/index.html");
    // Caching
    myWebView.getSettings().setDomStorageEnabled(true);
    String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
    myWebView.getSettings().setAppCachePath(appCachePath);
    myWebView.getSettings().setAllowFileAccess(true);
    myWebView.getSettings().setAppCacheEnabled(true);
}
public class WebAppInterface {
    public Context mContext;
    WebAppInterface(Context c) {
        mContext = c;
    }
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
    public void openActivity(String activity){
        Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(activity));
        mContext.startActivity(i);
    }
}
HTML:
<div class="entry" onclick="window.JSInterface.openActivity('About');">About</div>
                Add annotation @javascriptInterface over openActivity method.
@JavascriptInterface
public void openActivity(String activity){
    Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(activity));
    mContext.startActivity(i);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With