本文介绍了在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){}"
+ "};");
}
通过添加以下行为您的网页浏览启用Javascript
Enable Javascript for your webview by adding the following line
wb.getSettings().setJavaScriptEnabled(true);
这篇关于在Webview中运行javascript代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!