DevLog
Python, TypeScript, etc...
MyPage
Python, TypeScript, etc...
2022/07/02

Android WebviewとKotlin間の値渡し

AndroidKotlin
preview
@shiromisanta
Frontend Engineer
  •  /
目次
KotlinからJavaScriptを呼ぶ

KotlinからJavaScriptを呼ぶ

jsでwindowに関数を定義

window.hoge = function(arg) { return `arg: ${arg}` }

Kotlinから呼び出す。戻り値があれば第二引数のコールバックで受け取る

fun sample () { val arg = "example string" webView?.evaluateJavascript("window.sampleEvent(${arg})", ValueCallback<String> { result -> println(result) }) }

JavaScriptからKotlinを呼ぶ

@JavascriptInterfaceをつけた関数を持つクラスを定義

class MyJavaScriptInterface(private val context: Context) { @JavascriptInterface fun showToast(string: String) { Toast.makeText(context, string, Toast.LENGTH_SHORT).show() } }

Nativeという名前でWebView内のJSに注入

webView.addJavascriptInterface(MyJavaScriptInterface(this), "Native")

JSから呼び出し

Native.showToast('PushMe clicked!')

参考

  • https://tyfkda.github.io/blog/2014/11/03/android-gawa-native.html

関連記事

preview
@shiromisanta 2022/08/18
光学カメラAndroidKotlin
preview
@shiromisanta 2022/07/20
Kotlin
preview
@shiromisanta 2022/07/15
AndroidKotlin
preview
@shiromisanta 2022/07/15
AndroidKotlin
2022/07/02

Android WebviewとKotlin間の値渡し

AndroidKotlin

KotlinからJavaScriptを呼ぶ

jsでwindowに関数を定義

window.hoge = function(arg) { return `arg: ${arg}` }

Kotlinから呼び出す。戻り値があれば第二引数のコールバックで受け取る

fun sample () { val arg = "example string" webView?.evaluateJavascript("window.sampleEvent(${arg})", ValueCallback<String> { result -> println(result) }) }

JavaScriptからKotlinを呼ぶ

@JavascriptInterfaceをつけた関数を持つクラスを定義

class MyJavaScriptInterface(private val context: Context) { @JavascriptInterface fun showToast(string: String) { Toast.makeText(context, string, Toast.LENGTH_SHORT).show() } }

Nativeという名前でWebView内のJSに注入

webView.addJavascriptInterface(MyJavaScriptInterface(this), "Native")

JSから呼び出し

Native.showToast('PushMe clicked!')

参考

関連記事

preview
@shiromisanta
Frontend Engineer
  •  /
©︎Devlog