Run javascript code in Webview

From kitkat onwards use evaluateJavascript method instead loadUrl to call the javascript functions like below

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        webView.evaluateJavascript("var FunctionOne = function () {"
            + "  try{document.getElementsByClassName('test')[0].style.color="red";}catch(e){}"
            + "};", null);
    } else {
        webView.loadUrl("javascript:"
            + "var FunctionOne = function () {"
            + "  try{document.getElementsByClassName('test')[0].style.color="red";}catch(e){}"
            + "};");
    }

Enable Javascript for your webview by adding the following line

wb.getSettings().setJavaScriptEnabled(true);

Leave a Comment