Jeff Dege Jeff Dege - 6 months ago 26
Android Question

Debugging Android WebViews?

I'm trying to debug an Android app that makes heavy use of WebViews to display web pages from within the app.

The problem is simple - when I load the page, there's an anchor on one page that when clicked gives me a 404. The problem, it does this only when running the page from within the app's WebView. If I load the page in a desktop browser, or from within Chrome or from within the Android Browser on the mobile, I load the page just fine.

More confusingly, there's another anchor on the same page with the same basic architecture that's working just fine.

The URL for the anchor is being set via JQuery:

var url = ...;
$('#submitButton').attr('href', url);


When I load the page on a desktop browser, I can see the URL that the anchor points to, and it's correct. When I run the page within an app's WebView, I cannot see the URL that the anchor points to, so when it fails, I don't know why.

I'm currently running the website with VS2013 and IIS Express, with bindings and firewalls set so I can access it off my machine. I'm building the app in Android Studio 1.1.0, and am running the app within a GenyMotion emulator.

Is there any way I can examine the DOM of a web page loaded into a webview, so I can see exactly what URL we're trying to load? Or any way I can debug the javascript that is constructing that URL?

Answer

It is possible to configure a WebView so that console.log() messages show up in LogCat. You need to set a WebChromeClient on the WebView, then implement onConsoleMessage() in your client. From http://developer.android.com/guide/webapps/debugging.html:

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

That got me far enough to figure out what my problem was - the javascript that initialized the link depended upon LocalStorage, and LocalStorage and SessionStorage aren't enabled, in WebViews, by default. You need to enable it with a call to setDomStorageEnabled(). (You also need to enable javascript, but I'd already been doing that):

WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings settings = myWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);