dmSherazi
dmSherazi

Reputation: 3831

Load JavaScript in android webview using loadUrl()

I am using a webview in my activity to show a webpage and I am using javascript to hide the header.

I have tried the following script in chrome console and it works fine: document.getElementsByClassName('Header')[0].style.display = 'none';

When I use the same script in android webview the page gets cleared and it displays none which is the output of the script. (also received on Chrome console).

String s = (new StringBuilder())
  .append(" javascript:  document.getElementsByClassName('Header')[0].style.display = 'none';")
  .toString();
webView.loadUrl(s);

Upvotes: 2

Views: 960

Answers (1)

Gaurav Vachhani
Gaurav Vachhani

Reputation: 349

You can use below code -

    try {

        // Load the html into jsoup
        Document doc = Jsoup.connect("http://your-site.com/").get();

        // find and remove header
        Element header = doc.getElementById("your-header");
        header.remove();

        // find and remove footer
        Element footer = doc.getElementById("your-footer");
        footer.remove();

        // Load data into a WebView
        WebView wv = (WebView) findViewById(R.id.webView);
        WebSettings ws = wv.getSettings();
        ws.setJavaScriptEnabled(true);
        wv.loadData(doc.toString(), "text/html", "utf-8");

    } catch (IOException e) {
        e.printStackTrace();
    }

You will find latest Jsoup Library at this link.

The library can be added to gradle by adding the following dependency compile 'org.jsoup:jsoup:1.8.2'

Upvotes: 1

Related Questions