dustinos3
dustinos3

Reputation: 974

WebView not displaying correctly using javascript getElementsByClassName()

I have my WebView displaying the webpage for my Android application, but I don't want the header with the website title and ad to display. This is the code that I have written and I'm not sure why it is not removing the header in my WebView.

webView = (WebView) findViewById(R.id.main_webview);
    webView.setWebViewClient(new WebViewClient(){
        @Override
        public void onPageFinished(WebView view, String url) {
            webView.loadUrl("javascript:(function() { " +
                    "var head = document.getElementsByClassName('logo-wrapper colored-header').style.display='none'; " +
                    "})()");
        }

    });
    String url = "http://davisclipper.com";



    WebSettings.ZoomDensity zoomDensity = WebSettings.ZoomDensity.FAR;
    webView.getSettings().setJavaScriptEnabled(true);

    webView.getSettings().setDefaultTextEncodingName("utf-8");
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setDefaultZoom(zoomDensity);
    webView.getSettings().setSupportZoom(true);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.requestFocus(View.FOCUS_DOWN);
    webView.setHorizontalScrollBarEnabled(false);

    webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);

    webView.loadUrl(url);

Maybe there is something obvious that I'm doing wrong, but I'm wasting a lot of time trying to find an answer. Any help is appreciated.

Upvotes: 1

Views: 1543

Answers (1)

Derek Hopper
Derek Hopper

Reputation: 2258

If you're confident your JavaScript is executing on the page, you may just have a tiny error in your JavaScript code. That's why it appears to be doing nothing.

I believe document.getElementsByClassName returns an HTMLCollection, not just a single element. I don't think you can set style on that. Instead, you can grab the first element in the HTMLCollection and go from there.

Try something like this. It should work if you're only trying to hide only one element with those classes.

document.getElementsByClassName('logo-wrapper colored-header')[0].style.display='none'

If you end up needing to hide more than one element with those classes, you can try this:

document.getElementsByClassName('logo-wrapper colored-header').map(el => { el.style.display = 'none' })

Upvotes: 3

Related Questions