简体   繁体   中英

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 .

  • All redirects have happened
  • The page is visibly displayed, nothing has yet to load

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.

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) .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM