Created
November 19, 2019 06:53
-
-
Save HabaCo/64949ac459d568f05ae6c596ad5e56a1 to your computer and use it in GitHub Desktop.
WebView interaction with Html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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