If you are testing your web app with a device running Android 4.4 or higher, you can remotely debug your web pages in WebView
with Chrome Developer Tools, while continuing to support older versions of Android.
The format of the message might appear different depending on which version of Android you're using. On Android 2.1 and higher, console messages from the Android Browser are tagged with the name "browser". On Android 1.6 and lower, Android Browser messages are tagged with the name "WebCore".
Android's WebKit does not implement all of the console APIs available in other desktop browsers.
》 All the console APIs shown above are also supported when debugging inWebView
. If you're targeting Android 2.1 (API level 7) and higher, you must provide a
WebChromeClient
that implements the
onConsoleMessage()
method in order for console messages to appear in logcat. Then, apply the
WebChromeClient
to your
WebView
with
setWebChromeClient()
.
For example, to support API level 7, this is how your code for onConsoleMessage(String, int, String)
might look:
WebView myWebView = (WebView) findViewById(R.id.webview); myWebView.setWebChromeClient(new WebChromeClient() { public void onConsoleMessage(String message, int lineNumber, String sourceID) { Log.d("MyApplication", message + " -- From line " + lineNumber + " of " + sourceID); } });
However, if your lowest supported version is API level 8 or higher, you should instead implementonConsoleMessage(ConsoleMessage)
. For example:
WebView myWebView = (WebView) findViewById(R.id.webview); myWebView.setWebChromeClient(new WebChromeClient() { public boolean onConsoleMessage(ConsoleMessage cm) { Log.d("MyApplication", cm.message()
+ " -- From line " + cm.lineNumber()
+ " of " + cm.sourceId()
); return true; } });
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 above, a logcat message is printed that looks like this:
Hello World -- From line 82 of http://www.example.com/hello.html