user3973556
user3973556

Reputation:

Open an activity window in Android WebView passing a String in JavaScript?

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>

Upvotes: 4

Views: 5870

Answers (3)

Matt Goodwin
Matt Goodwin

Reputation: 85

I spent all day debugging a similar issue, I was getting the error:

"Uncaught TypeError: window.Android.openActivity is not a function"

I had set my annotated method to private by mistake.

Check your method signature to make sure it is public if you are going to be calling it from Javascript.

Upvotes: 0

Charles
Charles

Reputation: 139

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);
}

Upvotes: 3

CrazyOrr
CrazyOrr

Reputation: 307

The interfaceName you set in

myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");

is "Android", you should use it in

<div class="entry" onclick="window.Android.openActivity('About');">About</div>

Upvotes: 0

Related Questions