Last Updated: February 25, 2016
·
3.63K
· bboydflo

strategy to deal with css bugs in android webview

I am not going to present all the necessary hacks one should do in order to render html pages properly on different Android webview versions but today I came up with this idea and I would like to share it.

If you are working on a project that includes Android webview and you struggle with different bugs (mostly CSS bugs) because of missing features in the webview you could maybe set the user agent dynamically depending on the Android version you're running your app into.

Minimal Example:

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class WebViewActivity extends Activity {

private WebView webView;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);

    webView = (WebView) findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);

            //THE IMPORTANT PIECE HERE
            webView.getSettings().setUserAgentString("youruseragent"+Build.VERSION.RELEASE);

    webView.loadUrl("http://www.google.com");
}

}

On the javascript side I would suggest to use a function like the following:

function getAndroidVersion(userAgent) {
if(userAgent.indexOf("youruseragent") >= 0)
return parseFloat(userAgent.slice(userAgent.indexOf("youruseragent")+13));
//13="youruseragent".length()
else return -1;
};

With this above function you could get the Android Version with one decimal like 4.1 or 2.3 etc.
Of course you can manipulate the function to get the full Android version, example: 4.1.2 or 2.3.3 etc. by changing the function like below:

function getAndroidVersion(userAgent) {
if(userAgent.indexOf("youruseragent") >= 0)
return userAgent.slice(userAgent.indexOf("youruseragent")+13);
//13 = "youruseragent".length()
else return -1;
};

The function returns -1 if the user agent is not containing your custom user agent string "youruseragent".

In my case I changed for example an entire view because of a CSS bug (position fixed elements do not scroll vertically in Android versions < 3).

But this strategy can be used for all kinds of issues with different webview versions.

I hope it can help anyone, especially the ones who target older webview versions.