如何确定何时Android WebView完全加载? [英] How to determine when Android WebView is completely done loading?

查看:128
本文介绍了如何确定何时Android WebView完全加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何确定WebView 完全 何时完成加载。

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

让我来定义 完全

Let me define completely.


  • 所有重定向都已发生

  • 页面显示,没有任何内容尚未加载

这个问题的答案不好:

WebViewClient.onPageFinished() - 如果有重定向加载页面,则会多次触发。它也会在页面显示之前触发。

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

PictureListener.onNewPicture() - 每次屏幕更改时都会触发和AFAICT每个重定向。我怎么知道最后一个是哪个解雇?

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() - 与onPageFinished相同的问题。 (在David建议以下解决方案后添加)

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

Thread.sleep(5000) - 应该是显而易见的,为什么这样是不可接受的。

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

当然,上述有效的巧妙组合将是完美的。

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

为什么我想知道你问这个?
因为我想在webview 完全 完成加载后注入一些javascript 一次

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.

推荐答案

感谢David Caunt建议您查看回复标题。

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

我发现以下内容工作得很好:

I've found the following to work pretty well:

不要让webview执行HTTP请求,而是自己动手,以便检查HTTP状态代码重定向。按照重定向链。当您获得不是重定向的请求时,设置一个标志并通过 webview.loadDataWithBaseURL 将数据发送到webview。该标志在 WebViewClient.onPageFinished()中检查,因此它知道所有重定向都已完成。此时可以注入javascript。当然页面本身可能正在进行一些javascript操作,很难知道,因此在javascript中添加延迟(比如500ms)可以让DOM解决。 setTimeout(function(){/ * your code * /},500)

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

这篇关于如何确定何时Android WebView完全加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆