Home » Android » How can I see Javascript errors in WebView in an Android app?

How can I see Javascript errors in WebView in an Android app?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m trying to run javascript in WebView in an app. I’m developing on Nexus 7.

The html / javascript works fine on Chromium, but certain actions aren’t happening on the tablet. Is there a way of seeing if any of the javascript itself is failing on the tablet? A kind of console view?

How to&Answers:

You can actually receive the console messages from a WebView, which would allow you to catch the errors that it throws.

To do so:

  1. Enable JavaScript on your WebView
  2. Set a WebChromeClient
  3. Override onConsoleMessage

Example:

    final WebView webView = (WebView) findViewById(R.id.webview_terms_conditions);

    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            Log.d("MyApplication", consoleMessage.message() + " -- From line "
                    + consoleMessage.lineNumber() + " of "
                    + consoleMessage.sourceId());
            return super.onConsoleMessage(consoleMessage);
        }
    });

    webView.loadUrl(getString(R.string.url_terms_conditions));

Similar to what it says here, though that doc isn’t complete and it uses a deprecated method.


When running on Android KitKat, you can also enable remote debugging!

Answer:

You can use Remote Debugging WebViews

Chrome Devtools Remote Debugging

More info

Debug WebViews in your native Android apps using Chrome Developer Tools.

On Android 4.4 (KitKat) or later, use DevTools to debug WebView content in native Android applications.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    WebView.setWebContentsDebuggingEnabled(true);
}

Type chrome://inspect in pc browser
enter image description here

Answer:

You might be able to use Firebug lite. It’s just a bookmarklet so you can open it on any page.

Also, please search there are many other similar questions: