What's the difference between setWebViewClient vs. setWebChromeClient?
What's the difference between setWebViewClient
vs. 开发者_如何学JAVAsetWebChromeClient
in Android?
From the source code:
// Instance of WebViewClient that is the client callback.
private volatile WebViewClient mWebViewClient;
// Instance of WebChromeClient for handling all chrome functions.
private volatile WebChromeClient mWebChromeClient;
// SOME OTHER SUTFFF.......
/**
* Set the WebViewClient.
* @param client An implementation of WebViewClient.
*/
public void setWebViewClient(WebViewClient client) {
mWebViewClient = client;
}
/**
* Set the WebChromeClient.
* @param client An implementation of WebChromeClient.
*/
public void setWebChromeClient(WebChromeClient client) {
mWebChromeClient = client;
}
Using WebChromeClient allows you to handle Javascript dialogs, favicons, titles, and the progress. Take a look of this example: Adding alert() support to a WebView
At first glance, there are too many differences WebViewClient & WebChromeClient. But, basically: if you are developing a WebView that won't require too many features but rendering HTML, you can just use a WebViewClient
. On the other hand, if you want to (for instance) load the favicon of the page you are rendering, you should use a WebChromeClient
object and override the onReceivedIcon(WebView view, Bitmap icon)
.
Most of the times, if you don't want to worry about those things... you can just do this:
webView= (WebView) findViewById(R.id.webview);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
And your WebView will (in theory) have all features implemented (as the android native browser).
I feel this question need a bit more details. My answer is inspired from the Android Programming, The Big Nerd Ranch Guide (2nd edition).
By default, JavaScript is off in WebView. You do not always need to have it on, but for some apps, might do require it.
Loading the URL has to be done after configuring the WebView, so you do that last. Before that, you turn JavaScript on by calling getSettings()
to get an instance of WebSettings and calling WebSettings.setJavaScriptEnabled(true)
. WebSettings is the first of the three ways you can modify your WebView. It has various properties you can set, like the user agent string and text size.
After that, you configure your WebViewClient. WebViewClient is an event interface. By providing your own implementation of WebViewClient, you can respond to rendering events. For example, you could detect when the renderer starts loading an image from a particular URL or decide whether to resubmit a POST request to the server.
WebViewClient has many methods you can override, most of which you will not deal with. However, you do need to replace the default WebViewClient’s implementation of shouldOverrideUrlLoading(WebView, String)
. This method determines what will happen when a new URL is loaded in the WebView, like by pressing a link. If you return true, you are saying, “Do not handle this URL, I am handling it myself.” If you return false, you are saying, “Go ahead and load this URL, WebView, I’m not doing anything with it.”
The default implementation fires an implicit intent with the URL, just like you did earlier. Now, though, this would be a severe problem. The first thing some Web Applications does is redirect you to the mobile version of the website. With the default WebViewClient, that means that you are immediately sent to the user’s default web browser. This is just what you are trying to avoid. The fix is simple – just override the default implementation and return false.
Use WebChromeClient to spruce things up Since you are taking the time to create your own WebView, let’s spruce it up a bit by adding a progress bar and updating the toolbar’s subtitle with the title of the loaded page.
To hook up the ProgressBar, you will use the second callback on WebView: WebChromeClient
.
WebViewClient is an interface for responding to rendering events; WebChromeClient is an event interface for reacting to events that should change elements of chrome around the browser. This includes JavaScript alerts, favicons, and of course updates for loading progress and the title of the current page.
Hook it up in onCreateView(…)
. Using WebChromeClient to spruce things up
Progress updates and title updates each have their own callback method,
onProgressChanged(WebView, int)
and onReceivedTitle(WebView, String)
. The progress you receive from onProgressChanged(WebView, int)
is an integer from 0 to 100. If it is 100, you know
that the page is done loading, so you hide the ProgressBar by setting its visibility to View.GONE
.
Disclaimer: This information was taken from Android Programming: The Big Nerd Ranch Guide with permission from the authors. For more information on this book or to purchase a copy, please visit bignerdranch.com.
If you want to log errors from web-page, you should use WebChromeClient
and override its onConsoleMessage
:
webView.settings.apply {
javaScriptEnabled = true
javaScriptCanOpenWindowsAutomatically = true
domStorageEnabled = true
}
webView.webViewClient = WebViewClient()
webView.webChromeClient = MyWebChromeClient()
private class MyWebChromeClient : WebChromeClient() {
override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean {
Timber.d("${consoleMessage.message()}")
Timber.d("${consoleMessage.lineNumber()} ${consoleMessage.sourceId()}")
return super.onConsoleMessage(consoleMessage)
}
}
WebViewClient provides the following callback methods, with which you can interfere in how WebView
makes a transition to the next content.
void doUpdateVisitedHistory (WebView view, String url, boolean isReload)
void onFormResubmission (WebView view, Message dontResend, Message resend)
void onLoadResource (WebView view, String url)
void onPageCommitVisible (WebView view, String url)
void onPageFinished (WebView view, String url)
void onPageStarted (WebView view, String url, Bitmap favicon)
void onReceivedClientCertRequest (WebView view, ClientCertRequest request)
void onReceivedError (WebView view, int errorCode, String description, String failingUrl)
void onReceivedError (WebView view, WebResourceRequest request, WebResourceError error)
void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm)
void onReceivedHttpError (WebView view, WebResourceRequest request, WebResourceResponse errorResponse)
void onReceivedLoginRequest (WebView view, String realm, String account, String args)
void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error)
boolean onRenderProcessGone (WebView view, RenderProcessGoneDetail detail)
void onSafeBrowsingHit (WebView view, WebResourceRequest request, int threatType, SafeBrowsingResponse callback)
void onScaleChanged (WebView view, float oldScale, float newScale)
void onTooManyRedirects (WebView view, Message cancelMsg, Message continueMsg)
void onUnhandledKeyEvent (WebView view, KeyEvent event)
WebResourceResponse shouldInterceptRequest (WebView view, WebResourceRequest request)
WebResourceResponse shouldInterceptRequest (WebView view, String url)
boolean shouldOverrideKeyEvent (WebView view, KeyEvent event)
boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request)
boolean shouldOverrideUrlLoading (WebView view, String url)
WebChromeClient provides the following callback methods, with which your Activity
or Fragment
can update the surroundings of WebView
.
Bitmap getDefaultVideoPoster ()
View getVideoLoadingProgressView ()
void getVisitedHistory (ValueCallback<String[]> callback)
void onCloseWindow (WebView window)
boolean onConsoleMessage (ConsoleMessage consoleMessage)
void onConsoleMessage (String message, int lineNumber, String sourceID)
boolean onCreateWindow (WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg)
void onExceededDatabaseQuota (String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, WebStorage.QuotaUpdater quotaUpdater)
void onGeolocationPermissionsHidePrompt ()
void onGeolocationPermissionsShowPrompt (String origin, GeolocationPermissions.Callback callback)
void onHideCustomView ()
boolean onJsAlert (WebView view, String url, String message, JsResult result)
boolean onJsBeforeUnload (WebView view, String url, String message, JsResult result)
boolean onJsConfirm (WebView view, String url, String message, JsResult result)
boolean onJsPrompt (WebView view, String url, String message, String defaultValue, JsPromptResult result)
boolean onJsTimeout ()
void onPermissionRequest (PermissionRequest request)
void onPermissionRequestCanceled (PermissionRequest request)
void onProgressChanged (WebView view, int newProgress)
void onReachedMaxAppCacheSize (long requiredStorage, long quota, WebStorage.QuotaUpdater quotaUpdater)
void onReceivedIcon (WebView view, Bitmap icon)
void onReceivedTitle (WebView view, String title)
void onReceivedTouchIconUrl (WebView view, String url, boolean precomposed)
void onRequestFocus (WebView view)
void onShowCustomView (View view, int requestedOrientation, WebChromeClient.CustomViewCallback callback)
void onShowCustomView (View view, WebChromeClient.CustomViewCallback callback)
boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
精彩评论