Paulo Roberto Paulo Roberto - 6 months ago 168
Android Question

Hide elements on the page in webview Android

I want to load the site , but do not want to show

divHeader
, I've tried several ways and apparently the code I'm using does not have mistakes because there are no messages in
logcat
... How do I hide a particular Div.

package br.webview.com;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;


public class WebViewDevMobileActivity extends Activity {

private WebView myWebView;

private final String URL = "http://uniceu.prefeitura.sp.gov.br/";

@SuppressLint("SetJavaScriptEnabled")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.site);

if (!DetectConnection.checkInternetConnection(this)) {

Toast.makeText(getApplicationContext(), "Opa, parece que vc esta sem internet!", Toast.LENGTH_LONG).show();
} else {

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

myWebView.loadUrl(URL);
myWebView.getSettings().setBuiltInZoomControls(true);
}
}

@Override
public void onBackPressed() {
if(myWebView.canGoBack()) {
myWebView.goBack();
} else {
super.onBackPressed();
}
}
}


image

Answer

getElementById() returns single Node element. Try:

document.getElementById('divHeader').style.display='none'

To manipulate multiple elements would be better to add additional class to elements that should be hidden in WebView (__hiddenInWebView in this case), and then:

var items = document.querySelectorAll('.__hiddenInWebView');
for (index in items) {
    items[index].style.display = 'none';
}

if You can't modify DOM from webpage (add additional classes), then populate array with elements and hide them in a loop:

var items = [];
items.push(document.querySelector('#first'));
items.push(document.querySelector('#second'));
for (index in items) {
    items[index].style.display = 'none';
}