Skip to content

Instantly share code, notes, and snippets.

@HabaCo
Created November 19, 2019 06:53
Show Gist options
  • Save HabaCo/64949ac459d568f05ae6c596ad5e56a1 to your computer and use it in GitHub Desktop.
Save HabaCo/64949ac459d568f05ae6c596ad5e56a1 to your computer and use it in GitHub Desktop.
WebView interaction with Html
package com.habaco.test.js2webview
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.webkit.JavascriptInterface
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 讀取本地網頁
webView?.loadUrl("file:///android_asset/testJS.html")
// 允許 js
webView?.settings?.javaScriptEnabled = true
// 注入 js interface,js-object = android_app
webView?.addJavascriptInterface(JavaInterface(), "android_app")
button?.setOnClickListener {
val javascript = "javascript:mobileCallJs('${input?.text.toString()}')"
Log.i(">>>", "javascript --> $javascript")
// 版本判斷使用 javascript
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript(javascript, null)
} else {
webView.loadUrl(javascript)
}
}
}
inner class JavaInterface {
// 標記 javascript function
@JavascriptInterface
fun callAndroid(value: String) {
Toast.makeText(this@MainActivity, value, Toast.LENGTH_SHORT).show()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment