I am trying to inject some Javascript into my web view immediately after loading data into my web view via webView.loadDataWithBaseURL() but I have no way of knowing when the data is actually finished loading. Is this method synchronous? Can I just rely on the data being immediately loaded since it comes from memory? I'm asking because it seems as if my injected Javascript is not seeing elements on the page. I'm assuming it's because the view has not loaded before injecting the JS. (I have yet to prove this.)
Asked
Active
Viewed 1,047 times
2 Answers
0
You can register a WebViewClient with your WebView using setWebViewClient() and implement its onPageFinished() to know when the page is done loading.

Doug Stevenson
- 297,357
- 32
- 422
- 441
-
I've done all that. As I said above these callbacks are not being invoked when I use the loadDataWithBaseURL method to load my data from memory. My question is wether I can expect any callback or if the data is loaded immediately. – Cliff Mar 20 '16 at 23:02
-
You didn't mention onPageFinished or any other callbacks, so I went with the first obvious missing component. WebView renders async in its own threads, which is why you need to rely on the callbacks. If you have more specific data to share about what exactly you're doing and what's not working as expected, please update your question to reflect that. Adding code always helps. – Doug Stevenson Mar 20 '16 at 23:04
-
Oops, I suppose I didn't mention it, it was in my head but never made it into the post! My sincere apologies! Yes I have registered callbacks but none are being invoked. I believe there is something special about this way of loading web pages. – Cliff Mar 20 '16 at 23:07
-
If you look elsewhere on SO, the primary complaint has always been that the callbacks fire *too early* with loadData() (these complaints ended a few years ago, so maybe it's been fixed since). I'll try with a simple test app some time. – Doug Stevenson Mar 20 '16 at 23:08
-
@Cliff I made a simple test app, and I do get the onPageFinished callback when using loadData() with a simple HTML doc. Emulator API level 23. – Doug Stevenson Mar 20 '16 at 23:18
-
Hey thanks a ton for verifying Doug! I'll run a quick test in a simple app of my own then try to figure out the deltas. – Cliff Mar 20 '16 at 23:44
-
Looks like the callback WAS being called! I had some other stuff in my app confusing me. Thanks again! :) – Cliff Mar 21 '16 at 07:21
0
postVisualStateCallback
with custom WebViewClient
solved my problem:
class WebViewWithCallback(private val webView: WebView, private val callback: () -> Unit): WebViewClient(){
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
webView.postVisualStateCallback(0, object: WebView.VisualStateCallback() {
override fun onComplete(p0: Long) {
callback.invoke()
}
})
}
}

Ole Pannier
- 3,208
- 9
- 22
- 33