LoginSignup
1
2

More than 3 years have passed since last update.

【Androidアプリ開発】WebViewのJavaScriptからネイティブのメソッドを呼ぶ

Posted at

ウェブページをネイティブで包んだアプリを作る際などに、Web側からネイティブアプリ側に情報を渡したいことがある。
普通にJavascriptInterfaceを使えばよいのだが、少しハマった部分があったのでメモしておく。

実装方法

基本的には公式の下記のページが参考になる。
https://developer.android.com/guide/webapps/webview?hl=ja#BindingJavaScript

  • 呼び出されるメソッドの定義
MainActivity.kt
/** Instantiate the interface and set the context  */
    class WebAppInterface(private val mContext: Context) {

        /** Show a toast from the web page  */
        @JavascriptInterface
        fun showToast(toast: String) {
            Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show()
        }
    }
  • WebViewにインターフェースを追加
MainActivity.kt
val webView: WebView = findViewById(R.id.webview)
    webView.addJavascriptInterface(WebAppInterface(this), "Android")
  • 呼び出すJS
test.html
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

    <script type="text/javascript">
        function showAndroidToast(toast) {
            Android.showToast(toast);
        }
    </script>

ネイティブアプリ以外でも表示するサイトであれば、tryでくくってエラーが出ないようにしてあげた方がよさそう。

必要な記述

上記に従って実装してみたのだが動かない。
WebViewではデフォルトでJavaScriptが無効になっているようだ。
下記で有効にしてあげる必要があった。

MainActivity.kt
myWebView.getSettings().setJavaScriptEnabled(true)

おまけ

WebViewではストレージも無効になっていたので、必要な場合はオンにする。

MainActivity.kt
myWebView.getSettings().setDomStorageEnabled(true)
1
2
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
1
2