【发布时间】:2018-07-26 07:19:03
【问题描述】:
我已经尝试了几个小时在一个由Jsoup 解析的html 的android webview 中运行一些Javascript。尽管我尽一切努力让它发挥作用,但我仍然无法做到。
我已经在谷歌上搜索并尝试了我找到的所有答案,但是他们都没有做到我尝试使用方法的技巧,这就是我最终得到的结果:
Document doc = Jsoup.connect("http://example.com/").get();
Elements web_body = doc.select("body").first().children();
Elements web_head = doc.select("head").first().children();
String javascript = "document.querySelector('h1').innerText='f';"; //Replaces 'Example Domain' with 'f': just an example js code.
WebView webview = findViewById(R.id.webview_id);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
String html_content = "<html>" + "<head>" + web_head.toString() + "</head>" + "<body>" + web_body.toString() + "</body>" + "</html>";
webview.loadDataWithBaseURL("", html_content, "text/html", "UTF-8", "");
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webview.evaluateJavascript(javascript, null);
} else {
webview.loadUrl("javascript:(function(){" + javascript + "})()");
}
- 上面的代码显示了示例页面,但 javascript 根本不起作用:应用程序不显示任何错误消息或崩溃。
- 我使用的是 Android O (8.0) 手机。
希望以上信息对您有用。我仍然是 Java 的初学者,任何帮助将不胜感激!
【问题讨论】:
标签: javascript java android webview