Toufic Batache
Toufic Batache

Reputation: 802

Run JavaScript in Android webview

I've been trying for several hours to run some Javascript in an android webview in which there is html parsed by Jsoup. And despite all my attempts to make it work, I'm still not able to do it.

I've searched all over Google and tried all the answers I found, however none of them did the trick I tried using a method and here's what I ended up with:

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

I hope the above information will be useful. I'm still a beginner in Java and any help would be greatly appreciated!

Upvotes: 5

Views: 8038

Answers (1)

Toufic Batache
Toufic Batache

Reputation: 802

Well I replaced:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
    webview.evaluateJavascript(javascript, null);
} else {
    webview.loadUrl("javascript:(function(){" + javascript + "})()");
}

with

webview.setWebViewClient(new WebViewClient() {
    public void onPageFinished(WebView webview, String url) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            webview.evaluateJavascript(javascript, null);
        } else {
            webview.loadUrl("javascript:(function(){" + javascript + "})()");
        }
    }
});

and it just WORKS!

Upvotes: 7

Related Questions