Search code examples
javascriptandroidfontswebviewandroid-4.4-kitkat

WebView on Android 4.4 - Changing font using JavaScript


In one of my apps, I am getting HTML content and adding Javascript Images and loading the content with loadURL(). On clicking the image the injected respective javascript functions are called. The functions are to "Increase Font", "Decrease Font" & "Share".

The increase & decrease of font size is done using Javascript function WebView.loadUrl("javascript:getElementById('Title')... etc);

I recently changed my app target api as 19 (Android 4.4). Now i am noticing the WebPage becomes blank whenever increase or decrease of font size is called. However Share continues to work fine. I have added the @JavaScriptInterface annotation as required in Android 4.4.

(The whole setup was working when target was 16). Kindly advise if anyone have come across this issue.


Solution

  • On Android 4.4 and above, you can no longer load javascript in the loadUrl() WebView method. There is now a new method called evaluateJavascript(...) and it is used as follows:

    String javascript = "INSERT JAVASCRIPT";
    ValueCallback<String> resultCallback;
    
    // ...initialize resultCallback here
    
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        mWebView.evaluateJavascript(javascript, resultCallback);
    } else {
        mWebView.loadUrl(javascript);
    }