Skip to content

Instantly share code, notes, and snippets.

@shuantsu
Last active October 7, 2024 13:01
Show Gist options
  • Save shuantsu/e85613d55122282709d6a0d89893db40 to your computer and use it in GitHub Desktop.
Save shuantsu/e85613d55122282709d6a0d89893db40 to your computer and use it in GitHub Desktop.

KOTLIN WEBVIEW (HTML+CSS+JS HYBRID ANDROID APP)


Useful snippets

MainActivity.kt

val webView = findViewById<WebView>(R.id.webView)

webView.settings.javaScriptEnabled = true
webView.settings.domStorageEnabled = true
webView.settings.builtInZoomControls = true
webView.settings.displayZoomControls = false
webView.loadUrl("file:///android_asset/index.html")

webView.webViewClient = object : WebViewClient() {
    override fun onPageFinished(view: WebView, url: String) {
        webView.evaluateJavascript("document.getElementById('kotlin-test').innerText = 'KOTLIN BABYYYYYYYY'", null)
    }
}

androidmanifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  


<activity
  android:name=".MainActivity"
  android:configChanges="uiMode|screenSize|orientation|screenLayout|smallestScreenSize"
  android:exported="true">

Dark theme support for Css

@media (prefers-color-scheme: dark) {
  body {
    background-color: #333;
    color: pink;
  }
}

Useful links

JS override functions (alert, prompt, confirm)

https://stackoverflow.com/a/68794366

JS/Kotlin android function interface

https://developer.android.com/develop/ui/views/layout/webapps/webview?hl=pt-br#BindingJavaScript

https://stackoverflow.com/a/6357223

Execute JS from kotlin using webview.loadurl

https://stackoverflow.com/a/4330642

Kotlin Webview finished loading ("onLoad" trigger)

https://stackoverflow.com/a/67621998

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment