0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AndroidのWebViewで関数を呼ぶ方法

0
Last updated at Posted at 2026-10-04

AndroidのWebViewでKotlinとJavaScriptでそれぞれの関数を呼び出す方法をメモします。

class AndroidBridge(private val context: Context) {
    @JavascriptInterface
    fun showMessage(message: String) {
        Handler(Looper.getMainLooper()).post {
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
        }
    }
}

binding.webView.settings.javaScriptEnabled = true

binding.webView.addJavascriptInterface(
    AndroidBridge(requireContext()),
    "Android"
)

binding.webView.evaluateJavascript(
    "showMessage('Kotlinから送信')",
    null
)

// JavaScriptから戻り値を受け取る場合は以下のように書く
binding.webView.evaluateJavascript("addNumbers(10, 20)") { result ->
    val answer = result.toInt()
    println(answer)
}

KotlinからJavaScript関数を呼ぶ

KotlinからWebView内のJavaScriptを実行するには、JavaScriptを有効にし、evaluateJavascript() で関数を呼び出します。WebViewで読み込むHTMLにJavaScriptの関数を定義します。showMessage() は受け取った文字列をダイアログで表示し、addNumbers() は2つの数値を受け取り、合計値を返します。

function showMessage(message) {
    alert(message);
}

function addNumbers(a, b) {
    return a + b;
}

function sendMessageAndroid() {
    Android.showMessage("JavaScriptから送信");
}

JavaScriptからKotlin関数を呼ぶ

JavaScriptからAndroid側の関数を呼び出すには、addJavascriptInterface() を使用します。まずAndroid側でJavaScriptに公開する関数を持ったクラスAndroidBridgeを作成します。次に作成したクラスをWebViewに登録します。登録したKotlinの関数はJavaScriptから以下のように呼び出せます。

function sendMessageAndroid() {
    Android.showMessage("JavaScriptから送信");
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?