在 Webview 中运行 javascript 代码 [英] Run javascript code in Webview

查看:21
本文介绍了在 Webview 中运行 javascript 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在 android 中使用的 webview,我试图在单击按钮时触发 javascript.我正在尝试使用下面的代码将类的颜色更改为红色.但我似乎无法让它工作

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. But I cant seem to get it working

final WebView wb=(WebView)findViewById(R.id.webView2);
wb.loadUrl("javascript:"
                + "var FunctionOne = function () {"
                + "  try{document.getElementsByClassName('test')[0].style.color='red';}catch(e){}"
                + "};");

推荐答案

从 kitkat 开始,使用evaluateJavascript 方法代替loadUrl 来调用javascript 函数,如下所示

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){}"
            + "};");
    }

通过添加以下行为您的 webview 启用 Javascript

Enable Javascript for your webview by adding the following line

wb.getSettings().setJavaScriptEnabled(true);

这篇关于在 Webview 中运行 javascript 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆