Javascript Issues in Android WebView After Upgrading to Target SDK 29

I am attempting to display a local HTML file within a WebView as shown in the code snippet below:

context?.assets?.open("SeatingPlan.html")?.bufferedReader()?.use {
    val content = it?.readText()
    content?.let {
        val modifiedHTML = content.replace("{PERFORMANCE-ID}", occurrence.id.toString())
        binding.webView.addJavascriptInterface(SeatingPlanWebAppInterface { ticketInfo: String ->
            manageTicketSelection(ticketInfo)
        }, "Android")
        binding.webView.loadData(modifiedHTML, "text/html; charset=utf-8", "UTF-8")
    }
}

Following this, I’ve set up a listener to initiate some JavaScript functions after the content has loaded:

binding.webView.settings.javaScriptEnabled = true
binding.webView.webViewClient = object : WebViewClient() {
    override fun onPageFinished(view: WebView, url: String) {
        super.onPageFinished(view, url)
        binding.webView.loadUrl("javascript:(function() {" +
            "document.addEventListener('LTD.SeatPlan.OnSeatSelected', event => {Android.seatChosen(JSON.stringify(event.detail))});" +
            "document.addEventListener('LTD.SeatPlan.OnSeatUnselected', event => {Android.seatDeselected(JSON.stringify(event.detail))});" +
            "})();")
    }
}

Previously, this code operated correctly across all Android versions since 5.0, but now, after switching to target SDK 29, it hangs on loading the HTML and only displays a blank screen. I suspect this might be tied to the adjustments made in SDK 29. Can anyone suggest a solution, given the recent modifications to WebView?

The issue could be related to the new security and privacy changes introduced in SDK 29. If you’re encountering a blank screen, try inspecting the JavaScript console via remote debugging to catch any errors that might not be visible otherwise. Additionally, check if your local HTML file access might be restricted by the new storage policies. You might need to add the android:usesCleartextTraffic="true" attribute in your manifest if the file or any assets are not using HTTPS. Also, ensure all required permissions are correctly set and consider using loadDataWithBaseURL if accessing local resources, ensuring the base URL is specified correctly.