Remove DIV from a webpage for webview android using Jsoup

android-webview, jsoup

Solution

You can do this without using Jsoup you know. Just use plain old javascript. The following code will show how to remove an element from the HTML page and display the rest.

final WebView mWebView = (WebView) findViewById(R.id.mWebViewId);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
 @Override
public void onPageFinished(WebView view, String url)
{
mWebView.loadUrl("javascript:(function() { " +
    "document.getElementById('a')[0].style.display='none'; " +
    "})()");
}
});
mWebView.loadUrl(youUrl);

Problem

I want to partially view a webpage on webview android and remove some div element from the webpage. I have a webpage like this ``` <!DOCTYPE html> <body> <div id="a"><p>Remove aa</p></div> <div id="b"><p>bb</p></div> </body></html> ``` Now I want to remove the div with id 'a' from the webpage. I tried to code it with Jsoup but I am not well enough to make it out. Please see my full code: ``` import java.io.IOException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import android.os.Bundle; import android.app.Activity; import android.graphics.Bitmap; import android.webkit.WebView; import android.webkit.WebViewClient; public class CustomWebsite extends Activity { private WebView webView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custom_website); Document doc; String htmlcode = ""; try { doc = Jsoup.connect("http://skyasim.info/ab.html").get(); doc.head().getElementsByTag("DIV#a").remove(); htmlcode = doc.html(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } webView = (WebView) findViewById(R.id.webView_test); webView.setWebViewClient(new myWebClient()); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl("htmlcode"); } public class myWebClient extends WebViewClient { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // TODO Auto-generated method stub super.onPageStarted(view, url, favicon); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // TODO Auto-generated method stub view.loadUrl(url); return true; } } } ```

Original source