我在 Android 应用程序中使用 WebView。 WebViewClient 用于拦截目标“https://”REST 请求,以便我可以在 native 客户端进行一些自定义处理。
问题是 WebViewClient.shouldInterceptRequest(WebView, WebResourceRequest) 仅在应用程序第一次运行时被调用。对同一 REST 服务的后续网络请求不再调用 shouldInterceptRequest()。我必须卸载该应用程序或在应用程序信息系统设置中“清除存储”才能再次调用 shouldInterceptRequest()。
为了排除网站缓存服务响应的可能性,我使用 Charles Proxy 来监视网络流量。我可以看到每次加载网页时都会发出一个新的网络请求,无论是否触发了shouldInterceptRequest()。
第一次之后没有调用shouldInterceptRequest()可能是什么原因?
最佳答案
事实证明,我尝试嵌入的 Web 应用程序使用浏览器 Service Worker。 WebViewClient 无法拦截 Service Worker 发出的网络请求。为了拦截 Service Worker 网络请求,必须使用 ServiceWorkerClientCompat。
对我来说,解决方案是设置 WebServiceClient 和 ServiceWorkerClient,因为服务工作线程有自己的生命周期,并且在某些情况下可能不会被激活(例如第一次运行应用程序时)。
示例代码如下。
if (WebViewFeature.isFeatureSupported(WebViewFeature.SERVICE_WORKER_BASIC_USAGE)) {
ServiceWorkerControllerCompat.getInstance().setServiceWorkerClient(
object : ServiceWorkerClientCompat() {
override fun shouldInterceptRequest(request: WebResourceRequest): WebResourceResponse? {
// custom handling
}
})
}
关于Android的WebViewClient.shouldInterceptRequest()仅在第一次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59428205/