如何处理webview确认对话框?

时间:2010-04-28 02:01:08

标签: android dialog webview popup handle

我在WebView中显示网页,在网页上有一个按钮。当您单击该按钮时,应该弹出一个确认对话框,但它不会显示在我的WebView中。如果我在Android浏览器中访问同一个网页,它会弹出。任何人都知道如何处理来自WebView内部网页的弹出对话框?

2 个答案:

答案 0 :(得分:44)

好的,找到了答案,就在这里!

为了处理来自WebView中网页的弹出确认,您需要覆盖WebChromeClient中的onJsConfirm方法,以将弹出窗口显示为Android Alert对话框。这是代码。

final Context myApp = this; 
final class MyWebChromeClient extends WebChromeClient {
    @Override
    public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
        new AlertDialog.Builder(myApp)
        .setTitle("App Titler")
        .setMessage(message)
        .setPositiveButton(android.R.string.ok,
                new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int which)
            {
                result.confirm();
            }
        })
        .setNegativeButton(android.R.string.cancel,
                new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int which)
            {
                result.cancel();
            }
        })
        .create()
        .show();

        return true;
    }
}

不要忘记在WebView中设置WebChromeClient ......

    mWebView.setWebChromeClient(new MyWebChromeClient());

注意..这不是我的代码,但我找到了它,它非常适合在WebView中处理javascript确认对话框!

干杯!

答案 1 :(得分:1)

感谢Brockoli的方法。 我需要Xamarin.Android

 public class MyWebChromeClient : WebChromeClient
{
    private Context mContext;
    private JsResult res;

    public MyWebChromeClient(Context context)
    {
        mContext = context;
    }


     public override bool OnJsConfirm(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();

        return true;


        //return base.OnJsConfirm(view, url, message, result);
    }

    private void CancelAction(object sender, DialogClickEventArgs e)
    {
        res.Cancel();
    }

    private void OkAction(object sender, DialogClickEventArgs e)
    {
        res.Confirm();
    }
}

回到创建Webview的活动(web_view)

web_view.SetWebChromeClient(new MyWebChromeClient(this));