WebViewClient 和 WebChromeClient 是否互斥? [英] Are WebViewClient and WebChromeClient mutually exclusive?

查看:25
本文介绍了WebViewClient 和 WebChromeClient 是否互斥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从这个很好的解释关于之间的差异WebViewClientWebChromeClient 似乎如果你使用一个,你不应该使用另一个(对于同一个 WebView 对象).

我的理解正确吗?

如果不是,什么时候将 WebViewClient WebChromeClient 用于同一个 WebView 对象?

是否有一个例子,只对同一个 WebView 对象同时使用 WebViewClient WebChromeClient会完成某个目标吗?

解决方案

你当然可以同时使用两者,只是它们的功能不同.设置自己的自定义WebViewClient 可以处理onPageFinished、shouldOverrideUrlLoading 等,WebChromeClient 可以处理Javascript 的alert() 等函数.

只需创建自己的类,例如:

public class MyWebChromeClient extends WebChromeClient {//处理javascript警报:@覆盖public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result){Log.d("警报", 消息);Toast.makeText(context, message, 3000).show();结果.确认();返回真;};...

和/或

public class MyWebViewClient extends WebViewClient {@覆盖//在每一页上运行脚本,类似于Greasemonkey:public void onPageFinished(WebView view, String url) {view.loadUrl("javascript:alert('hi')");}...

只需覆盖文档中描述的功能,然后在 onCreate 中设置您的客户端:

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

From this great explanation about the differences between WebViewClient and WebChromeClient it seems that if you use one, you shouldn't be using the other (for the same WebView object).

Is my understanding correct?

If not, when would one use both WebViewClient and WebChromeClient for the same WebView object?

Is there an example of a situation where only use both WebViewClient and WebChromeClient for the same WebView object would accomplish a certain goal?

解决方案

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());

这篇关于WebViewClient 和 WebChromeClient 是否互斥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆