Carlos Rendon
Carlos Rendon

Reputation: 6232

How to determine when Android WebView is completely done loading?

I want to know how to determine when a WebView is completely done loading.

Let me define completely.

Bad answers to this question:

WebViewClient.onPageFinished() - this fires multiple times if there are redirects loading a page. It also fires before the page is displayed.

PictureListener.onNewPicture() - this fires every time the screen changes and AFAICT each redirect. How would I know which firing is the final one?

WebChromeClient.onProgressChanged() - same problem as onPageFinished. (Added after David suggested this solution below)

Thread.sleep(5000) - should be obvious, why this isn't acceptable.

Of course, a clever combination of the above that works would be perfect.

Why do I want to know this you ask? Because I want to inject some javascript one time once the webview is completely done loading.

Upvotes: 29

Views: 12833

Answers (2)

Carlos Rendon
Carlos Rendon

Reputation: 6232

Thanks to David Caunt for his suggestion to look at the response headers.

I've found the following to work pretty well:

Instead of having webview perform the HTTP requests, do them yourself so you can check the HTTP status code for redirects. Follow the redirection chain. When you get to a request that is not a redirect set a flag and send the data to the webview via webview.loadDataWithBaseURL. The flag is checked in WebViewClient.onPageFinished() so it knows that all redirects are done. The javascript can be injected at this point. Of course the page itself might be doing some javascript manipulation at this point, it is difficult to know, so adding a delay (say 500ms) to the javascript allows for the DOM to settle. setTimeout(function(){/* your code */}, 500).

Upvotes: 9

David Snabel-Caunt
David Snabel-Caunt

Reputation: 58371

Have you looked at setting your own WebChromeClient?

It looks like onProgressUpdated might inform you when a page has fully loaded.

This appears to be the method used by Android's built-in browser.

Upvotes: 1

Related Questions