Pezcraft
Pezcraft

Reputation: 299

How to return Android's Alert return value to WebView with JavascriptInterface?

I have created a Android WebView App for my browsergame. I use a Javascript-Alert to ask the user if he really wants to reset the score. But I want to use the Android Alert instead of the Javascript Alert. So I have created a Javascript Interface.

public class AlertJSInterface {
private Context context;

AlertJSInterface(Context c) {
    context = c;
}

@JavascriptInterface
public boolean alert(String title, String message) {
    AlertDialog.Builder alert = new AlertDialog.Builder(context);
    alert.setTitle(title);
    alert.setMessage(message);
    alert.setCancelable(true);
    alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });
    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });
    alert.show();

    //want to return true if clicked ok
}

Now i need the return value of the Android Alert inside Javascript. The problem is that the Android Alert has a ClickListener. But how can I get the value an return it to Javascript?

if(AndroidAlert.alert(resetScoreTitle, resetScoreAck) === true) {
    resetAll();
}

Upvotes: 0

Views: 542

Answers (1)

Randyka Yudhistira
Randyka Yudhistira

Reputation: 3652

What if you call js function after user click the "OK" button. It's like :

alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
       myWebView.loadUrl("javascript:resetAll();");
    }
});

Upvotes: 1

Related Questions