community icon indicating copy to clipboard operation
community copied to clipboard

Discussion: Get Cookies

Open aksy2512 opened this issue 2 years ago • 1 comments

Discussion: Get Cookies

This issue has been made to discuss getting cookies from the Chrome browser in your phone in your Flutter application which uses Dart.

Summary

I am building an application which gives insights into the security of a user, The application requires to get the details of the cookies stored but I am not able to find any libraries in dart which can do this, Please help me to find a solution for this

aksy2512 avatar Aug 22 '23 05:08 aksy2512

  1. Using Cooking Manager Class

`

 class CookieService {

          static const MethodChannel _channel = MethodChannel('com.yourapp/cookies');

         Future<String> getCookies(String url) async {
              try {
                final String cookies = await _channel.invokeMethod('getCookies', {'url': url});
                return cookies;
                  } on PlatformException catch (e) {
                     return "Failed to get cookies: '${e.message}'.";
            }
         }
    }

` 2. In the MainActivity or a custom plugin, implement the method to fetch cookies.

`

  import android.webkit.CookieManager
 
  import io.flutter.embedding.android.FlutterActivity
           
  import io.flutter.plugin.common.MethodChannel

  import android.os.Bundle

  class MainActivity : FlutterActivity() {
        private val CHANNEL = "com.yourapp/cookies"

          override fun onCreate(savedInstanceState: Bundle?) {
                        
                        super.onCreate(savedInstanceState)

                 MethodChannel(flutterEngine?.dartExecutor, CHANNEL).setMethodCallHandler { call, result ->
        if (call.method == "getCookies") {
            val url = call.argument<String>("url")
            if (url != null) {
                val cookies = getCookies(url)
                result.success(cookies)
            } else {
                result.error("UNAVAILABLE", "URL not provided", null)
            }
        } else {
            result.notImplemented()
        }
    }
}

private fun getCookies(url: String): String {
    val cookieManager = CookieManager.getInstance()
    return cookieManager.getCookie(url) ?: "No cookies found"
}

}

`

  1. Once the platform channel is set up, you can call the method like this:

`

void getCookiesFromBrowser() async {
      final cookieService = CookieService();
      final cookies = await cookieService.getCookies("https://www.example.com");
      print("Cookies: $cookies");
 }

`

MuhammadShoaib495 avatar Dec 17 '24 09:12 MuhammadShoaib495