5

I am loading the content of a local html file into a WebView:

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

Then, I have a listener so as I will trigger some javascript functions once the loading is finished as follows:

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', e => {Android.seatSelected(JSON.stringify(e.detail))});" + "document.addEventListener('LTD.SeatPlan.OnSeatUnselected', e => {Android.seatUnSelected(JSON.stringify(e.detail))});" + "})();")
        }
    }

The same code has been working well for all supported android versions of my app (5.0+), while now, after updating to target sdk 29 it gets stuck in loading the html and instead it shows a blank white screen.

I am thinking that the issue may be related to the changes made for SDK 29 , but don't know where else to look for a solution. The reason I am thinking it may be the target SDK 29 the issue is because of the latest changes relating to the WebView that were made: https://developer.android.com/about/versions/pie/android-9.0-migration. Is there a workaround?

Galatia
  • 51
  • 1
  • 7

2 Answers2

3

This change is part of the behavioral changes of Android Pie (28).

But, surprisingly the WebView with JS will work in all devices if the targetSdk version is set to 28. When you change it to 29, it stops working in all real devices but it will still work in emulators.

You need to call the static method setDataDirectorySuffix before initializing your WebView to get this working.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    WebView.setDataDirectorySuffix("your-suffix");
}
rahulrvp
  • 2,006
  • 1
  • 19
  • 26
0

In my case, update SDK version 28 to 29 webview not working . But in SDK version 28 working fine. After that I change my code it is working in SDK version 29

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        WebViewClientImpl webViewClient = new WebViewClientImpl(this);
        webView.setWebViewClient(webViewClient);
        webView.setWebChromeClient(new WebChromeClient());
        webView.loadDataWithBaseURL(null,html_content,"text/html","UTF-8",null);
Ganesan J
  • 539
  • 7
  • 12