1

I know how to call Java method in JavaScript code. It is done by @JavascriptInterface annotation. But what if I want to determine by Android which method from JS should be called? I'm calling an Android Dialog in JS using the mentioned annotation where I've got the switch statement which should determine which function should be called in JS. I used a flag which is not working because Dialogs are not synchronized so the method showDialog() is done before even Dialog starts. Is there any way to reach the Android-JS communication on the opposite side?

@JavascriptInterface
public int showDialog(){
    new AlertDialog.Builder(this.activity)
            .setTitle("Share iamge as...")
            .setItems(new CharSequence[]{"Image", "PDF document", "Print"}, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which){ // this switch should determine which JS function I call
                        case 0: chosenMethod = 0; // here should be called JS function (eg. exportImage() from JS code)
                            Log.v("Dialog onClick()", "method chosen" + chosenMethod);
                            break;
                        case 1: chosenMethod = 1;
                            Log.v("Dialog onClick()", "method chosen" + chosenMethod);
                            break;
                        case 2: chosenMethod = 2;
                            Log.v("Dialog onClick()", "method chosen" + chosenMethod);
                            break;
                    }
                }
            })
            .create().show();
    Log.v("Dialog out of onClick", "method chosen" + chosenMethod);
    return chosenMethod;
}
2
  • do you want to know how to call JS in WebView? Commented Sep 4, 2017 at 11:22
  • @VladMatvienko yeah, gonna post some code Commented Sep 4, 2017 at 11:26

1 Answer 1

1

You can do

webView.loadUrl("javascript:doSomething()");

any time after a webpage was loaded in your webview, to run a JS function.

If it doesn't work: check your webview settings (security / js).

Sign up to request clarification or add additional context in comments.

4 Comments

Should I pass my WebView to the method or there is another option to call loadUrl on it?
You'd better open the dialog in your presenter/activity/fragment, and use a callback in the dialog, back to its creator. The callback implementation in the presenter/activity/fragment can do the JS call on the WebView. But this is actually another question. Good luck
It is working like a charm, but I got one problem when I call the function: Uncaught ReferenceError: methodName is not defined
Should javascript be instead name of the script from which I call method?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.