Stan
Stan

Reputation: 963

Hiding div in Android WebView app with java doesn't work

I have a div called downloadapp that I'd like to display to users who visit my mobile website instead of using my Android app. So I need to hide that div for users who already use my app.

My code:

private void startWebView(String url) {
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {      

    //On error, open local file
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
    webView.loadUrl("file:///android_asset/www/myerrorpage.html");
    }

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

    @Override
    public void onPageFinished(WebView view, String url) {
        view.loadUrl("javascript:document.getElementById('downloadapp').style.display = 'none';");
    }   

});

webView.loadUrl(url);

}

Problem:

My app loads the div first and its actually being displayed for a couple of seconds. Then suddenly, the whole webpage loaded in the app disappears and a blank page with the word "none" is the only thing that is left on the screen.

Is there something wrong with the way I try to hide the div "downloadapp" or what am I missing here?

What I want it to do is immediately hide the div before the webpage is being displayed.

Upvotes: 1

Views: 880

Answers (1)

Mikhail Naganov
Mikhail Naganov

Reputation: 6881

This is happening on newer versions of WebView -- if your app is targeting API level 19 or above (KitKat), then if a javascript: URL returns a value, this value is interpreted as content for a new web page to open. In your case, as 'none' is the return value of the assignment, it is used as the content for a new page.

Just put void(0); at the end of your code in javascript: to prevent it from returning a value.

Upvotes: 2

Related Questions