DevWithZachary
DevWithZachary

Reputation: 3675

Show loading icon when loading webview page AND javascript into page

I have a webView in which a external website is loaded. Currently I have the below which will display a loading icon while the page has finished loading:

webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return false;
            }
            public void onPageStarted(WebView view, String url, Bitmap favicon)
            {
                super.onPageStarted(view, url, favicon);
                progressBar.setVisibility(View.VISIBLE);
            }
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub
                super.onPageFinished(view, url);
                progressBar.setVisibility(View.GONE);
                if (webView.canGoBack()){
                    left.setImageResource(R.drawable.ic_arrowleft);
                }else{
                    left.setImageResource(R.drawable.ic_arrowleft_gray);
                }
                if (webView.canGoForward()){
                    right.setImageResource(R.drawable.ic_arrowright);
                }else{
                    right.setImageResource(R.drawable.ic_arrowright_gray);
                }

            }
        });  

This works well, however in the same activity there is a button the user can press which will load some javascript into the currently loaded webpage. What I need is for the progress icon to display while the javascript is loading to.

private OnClickListener OnClick_script = new OnClickListener() {
        public void onClick(View v) {
            webView.loadUrl("javascript: function .....);
        }
    };

Upvotes: 0

Views: 3372

Answers (1)

linakis
linakis

Reputation: 1231

You could achieve what you want using a javascript WebAppInterface as demostrated here.

The main concept is that, you create a javascript interface

private class ShowProgressInterface {
    ProgressBar progressBar;


    ShowProgressInterface(ProgressBar progressBar) {
        this.progressBar = progressBar;
    }

    @JavascriptInterface
    public void showProgress() {
        progressBar.setVisibility(View.VISIBLE);
    }

    @JavascriptInterface
    public void hideProgress() {
        progressBar.setVisibility(View.GONE);
    }
}

Add the interface to your webView

webView.addJavascriptInterface(new ShowProgressInterface(progressBar), "ProgressInterface");

Finally in your javascript function you can call

ProgressInterface.showProgress();

and

ProgressInterface.showProgress();

Upvotes: 1

Related Questions