You can debug your JavaScript using the console JavaScript APIs and view the
output messages in Logcat. If you're familiar with debugging web pages with
Firebug or Web Inspector, then you're probably familiar with using console
(such as console.log()). Android's WebKit framework supports most of the same
APIs, so you can receive logs from your web page when debugging in your
WebView. This section describes how to use the console APIs for
debugging.
Use console APIs in WebView
The console APIs are also supported when debugging in WebView. You must
provide a WebChromeClient that implements the
onConsoleMessage() method for console messages to appear in Logcat.
Then, apply the WebChromeClient to your WebView with
setWebChromeClient(). For more information, see the WebView
documentation.
The following example shows how to use console APIs in WebView:
Kotlin
val myWebView: WebView = findViewById(R.id.webview)
myWebView.webChromeClient = object : WebChromeClient() {
override fun onConsoleMessage(message: ConsoleMessage): Boolean {
Log.d("MyApplication", "${message.message()} -- From line " +
"${message.lineNumber()} of ${message.sourceId()}")
return true
}
}
Java
WebView myWebView = findViewById(R.id.webview);
myWebView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Log.d("MyApplication", consoleMessage.message() + " -- From line " +
consoleMessage.lineNumber() + " of " + consoleMessage.sourceId());
return true;
}
});
The ConsoleMessage also includes a MessageLevel object
to indicate the type of console message being delivered. You can query the
message level with messageLevel() to determine the severity of the
message, then use the appropriate Log method or take other appropriate
actions.
Whether you're using
onConsoleMessage(String, int, String) or
onConsoleMessage(ConsoleMessage), when you execute a console method in
your web page, Android calls the appropriate onConsoleMessage() method so
you can report the error. For example, with the example code, a Logcat message
is printed that looks like this:
Hello World -- From line 82 of http://www.example.com/hello.html
The following are additional resources related to debugging:
Test experimental web features
Similar to Google Chrome's chrome://flags page, you can also test experimental
web features in WebView.
To do this, take the following steps:
Install one of the
WebViewpre-release channels (beta, dev, or canary){:.external}.Switch the
WebViewchannel on your test device to the installed pre-release channel.Click the WebView DevTools launcher.
Figure 1. WebView DevTools icon for app installed on a device. From DevTools, click the Flags item and search for any experimental features you'd like to enable or disable. The change applies to all
WebViewinstances on the device.Stop and restart your app to start testing with the new features.
For more information about toggling flags, see the
WebView DevTools documentation.