Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WebView: display only some part of website

I wanted to know if it was possible to display only certain parts of a website in a WebView. For example I have this website with the following html:

<html>
 <body>
<div id="1">ID 1</id>
<div id="2">ID 2</id>
<div id="3">ID 3</id>
</body>
</html>

it is possible to display in WebView only, for example, the contents of the div with id="3"? My code is WebWiew:

WebViewClient WebClient = new WebViewClient(){
        public boolean shouldOverrideUrlLoading(WebView view, String url){
          view.loadUrl(url);
          return true;
        }
    };


    WebView myWebView = (WebView) findViewById(R.id.webView1);
    myWebView.getSettings().setJavaScriptEnabled(true);
    myWebView.getSettings().setBuiltInZoomControls(true);
    myWebView.getSettings().setBuiltInZoomControls(true);
    myWebView.setWebViewClient(WebClient);
    myWebView.loadUrl("https://www.example.com");
like image 481
Enzo Avatar asked Jan 20 '13 11:01

Enzo


2 Answers

You can do this by extending WebViewClient and injecting some javascript which will render your web Page

public class MyWebClient extends WebViewClient {

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    view.loadUrl(url);
    return true;
}

@Override
public void onPageFinished(WebView view, String url) {
    view.loadUrl("javascript:your javascript");
}
}
.........
final MyWebClient myWebViewClient = new MyWebClient();
mWebView.setWebViewClient(myWebViewClient);

For hiding elements use view.loadUrl("javascript:document.getElementById(id).style.display = 'none';)

More info In Android Webview, am I able to modify a webpage's DOM?

like image 174
Roman Nazarevych Avatar answered Nov 08 '22 03:11

Roman Nazarevych


The most basic thing to understand here is whether the element we are referring to inside the web html file is a class or a id. If it is a id then getElementById works perfectly. If it is a class then getElementsByClassName is required.

Following is an example that I am using.

myWebView.loadUrl
      ("javascript:(function() { " +
           "document.getElementsByClassName('header_wrapper')[0].style.display='none'; " +
           "document.getElementsByClassName('footer-contact')[0].style.display='none'; "+
           "document.getElementsByClassName('navbar-header')[0].style.display='none'; "+
           "document.getElementsByClassName('footer-social')[0].style.display='none'; "+
           "document.getElementById('footer_bottom').style.display='none'; "+
           "document.getElementById('footer_content').style.display='none'; "+
           "document.getElementById('core_mobile_menu').style.display='none'; "+
           "document.getElementById('catapult-cookie-bar').style.display='none'; "+
       "}
      )()");
like image 34
Hasan Sawan Avatar answered Nov 08 '22 04:11

Hasan Sawan