How To Handle A Webview Confirm Dialog?
I'm displaying a webpage in a WebView and on the webpage, there is a button. When you click the button, a confirmation dialog is supposed to popup, but it doesn't show in my WebVi
Solution 1:
Ok, found the answer and here it is!
In order to handle a popup confirmation coming from a webpage in your WebView, you need to override the onJsConfirm method in WebChromeClient to display the popup as an Android Alert dialog. Here is the code to do so.
finalContextmyApp=this;
finalclassMyWebChromeClientextendsWebChromeClient {
@OverridepublicbooleanonJsConfirm(WebView view, String url, String message, final JsResult result) {
newAlertDialog.Builder(myApp)
.setTitle("App Titler")
.setMessage(message)
.setPositiveButton(android.R.string.ok,
newDialogInterface.OnClickListener()
{
publicvoidonClick(DialogInterface dialog, int which)
{
result.confirm();
}
})
.setNegativeButton(android.R.string.cancel,
newDialogInterface.OnClickListener()
{
publicvoidonClick(DialogInterface dialog, int which)
{
result.cancel();
}
})
.create()
.show();
returntrue;
}
}
Don't forget to set your WebChromeClient in your WebView...
mWebView.setWebChromeClient(newMyWebChromeClient());
Note.. this isn't my code, but I found it and it works perfectly for handling javascript confirmation dialogs in a WebView!
Cheers!
Solution 2:
Thanks Brockoli for the method. I needed this for Xamarin.Android
publicclassMyWebChromeClient : WebChromeClient
{
private Context mContext;
private JsResult res;
publicMyWebChromeClient(Context context)
{
mContext = context;
}
publicoverrideboolOnJsConfirm(WebView view, string url, string message, JsResult result)
{
res = result;
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.SetTitle("Confirm:");
builder.SetMessage(message);
builder.SetPositiveButton(Android.Resource.String.Ok, OkAction);
builder.SetNegativeButton(Android.Resource.String.Cancel, CancelAction);
builder.Create();
builder.Show();
returntrue;
//return base.OnJsConfirm(view, url, message, result);
}
privatevoidCancelAction(object sender, DialogClickEventArgs e)
{
res.Cancel();
}
privatevoidOkAction(object sender, DialogClickEventArgs e)
{
res.Confirm();
}
}
This back in the activity where webview is created (web_view)
web_view.SetWebChromeClient(newMyWebChromeClient(this));
Post a Comment for "How To Handle A Webview Confirm Dialog?"