Run javascript code in Webview

后端 未结 2 1471
孤街浪徒
孤街浪徒 2020-12-01 05:49

I have a webview i am using in android and I\'m trying to trigger javascript on a button click. I\'m trying to use the code below to change the color of the class to red. Bu

2条回答
  •  悲哀的现实
    2020-12-01 06:22

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

提交回复
热议问题