Are WebViewClient and WebChromeClient mutually exclusive?

前端 未结 2 1556
太阳男子
太阳男子 2020-12-07 11:13

From this great explanation about the differences between WebViewClient and WebChromeClient it seems that if you use one, you shouldn\'t be using t

2条回答
  •  攒了一身酷
    2020-12-07 11:34

    You certainly can use both, they just have different functions. Setting your own custom WebViewClient lets you handle onPageFinished, shouldOverrideUrlLoading, etc., WebChromeClient lets you handle Javascript's alert() and other functions.

    Just make your own class, for example:

    public class MyWebChromeClient extends WebChromeClient {
        //Handle javascript alerts:
        @Override
    public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result)  
    {
      Log.d("alert", message);
      Toast.makeText(context, message, 3000).show();
      result.confirm();
      return true;
    };
    ...
    

    and / or

    public class MyWebViewClient extends WebViewClient {
    @Override
        //Run script on every page, similar to Greasemonkey:
    public void onPageFinished(WebView view, String url) {
            view.loadUrl("javascript:alert('hi')");
        }
    ...
    

    Just override the functions described in the documentation, then set your client in onCreate with:

    webview.setWebViewClient(new MyWebViewClient());
    webview.setWebChromeClient(new MyWebChromeClient());
    

提交回复
热议问题