I\'m trying to get the height of a webview once it has been rendered. It always returns null, I\'ve tried getHeight, getMeasuredHeight, getCo
I found this solution to be 100% reliable.
Subclass your WebView and there is a need to invoke javascript after the content has been loaded.
// callback made this way in order to get reliable html height and to avoid race conditions
@SuppressLint("SetJavaScriptEnabled")
override fun onPageFinished(view: WebView?, url: String?) {
view?.let {
it.settings.javaScriptEnabled = true
it.addJavascriptInterface(WebAppInterface(it), "AndroidGetHeightFunction")
it.loadUrl("javascript:AndroidGetHeightFunction.resize(document.body.scrollHeight)")
}
}
We can then get proper height and disable javascript in callback (for security and consistency):
inner class WebAppInterface(private val webView: WebView) {
@JavascriptInterface
fun resize(height: Float) {
webView.post {
heightMeasuredListener?.invoke(formatContentHeight(webView, height.toInt()))
webView.settings.javaScriptEnabled = false
}
}
}
WebView must call post() as the code inside resize(...) is called in WebView thread!
After, make sure to scale your pixels to match density pixels!:
fun formatContentHeight(webView: WebView, height: Int): Int = Math.floor((height * webView.context.resources.displayMetrics.density).toDouble()).toInt()