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のCookie操作まとめ

0
Posted at

はじめに

AndroidアプリでWebViewを使用する際、Cookieに関する処理を行いたいケースがあります。
Cookieはセッション管理などに利用されるため、適切に扱うことが重要になります。

そこで本記事では、WebViewのCookie操作についてまとめます。

WebViewのCookie取得

AndroidではCookieManagerを使用してCookieを取得できます。

val cookieManager = CookieManager.getInstance()
val cookie = cookieManager.getCookie("https://example.com")

複数のCookieは;区切りの文字列として返却されます。

key1=value1; key2=value2

Composeでの実装例

ComposeでWebViewを使用する場合はAndroidViewを利用します。

@Composable
fun WebViewScreen(
    url: String,
    onCookieReceived: (String?) -> Unit
) {
    val context = LocalContext.current

    AndroidView(
        factory = {
            WebView(context).apply {
                settings.javaScriptEnabled = true

                webViewClient = object : WebViewClient() {
                    override fun onPageFinished(view: WebView?, url: String?) {
                        url?.let {
                            val cookie = CookieManager.getInstance().getCookie(it)
                            onCookieReceived(cookie)
                        }
                    }
                }

                loadUrl(url)
            }
        }
    )
}

ポイント

  • Cookie取得はonPageFinishedで行う
  • URLを指定して取得する
  • 取得結果は文字列

注意点

Cookie取得のタイミング

以下のタイミングではCookieが取得できないことがあります。

  • ページ読み込み前
  • ログイン処理完了前

基本はonPageFinishedで取得します。


ドメインの違い

Cookieはドメイン単位で管理されるため、取得時のURLが一致していないと取得できません。


Cookieの更新タイミング

リダイレクト直後などは、Cookieがまだ反映されていない場合があります。
必要に応じて再取得するなどの対応が必要です。


Cookie削除

セッションを破棄したい場合はCookieを削除します。

CookieManager.getInstance().removeAllCookies(null)

Cookieの反映

Cookieの更新は非同期で行われるため、取得タイミングによっては最新状態が取得できない場合があります。
確実に反映させたい場合は、以下のようにflush()を呼び出すことも検討できます。

CookieManager.getInstance().flush()

まとめ

WebViewのCookie取得は以下の流れで実装できます。

  • CookieManager.getCookie()で取得
  • onPageFinishedで取得する

WebViewとネイティブの連携においてCookieは重要な役割を持つため、基本的な扱いを理解しておくと実装がスムーズになります。

さいごに

花粉症が爆発しています、目が開けられません…

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?