Monday 24 October 2016

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);

Answer



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'


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...