小编Tou*_*che的帖子

在Android Webview中运行JavaScript

我已经尝试了好几个小时才能Javascript在html解析的android webview中运行某些内容Jsoup。尽管我竭尽全力使它起作用,但我仍然无法做到这一点。

我已经在整个Google上进行了搜索,并尝试了所有发现的答案,但是没有一个人尝试使用一种方法来达到我的目的,这就是我最终得到的结果:

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 + "})()");
} …
Run Code Online (Sandbox Code Playgroud)

javascript java android webview

2
推荐指数
1
解决办法
2536
查看次数

标签 统计

android ×1

java ×1

javascript ×1

webview ×1