Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flutter Web read cookies #745

Closed
incon opened this issue Apr 18, 2020 · 4 comments
Closed

Flutter Web read cookies #745

incon opened this issue Apr 18, 2020 · 4 comments

Comments

@incon
Copy link

incon commented Apr 18, 2020

I'm wanting to read a cookie. A system I'm working with requires me to read a cookie value and return it as a HTTP header to prevent CSRF. It appears there is currently no way to get the cookie value from the response when using the web platform.

@incon
Copy link
Author

incon commented Apr 20, 2020

I ended up using 'dart:html' to read browser cookies.

@incon incon closed this as completed Apr 20, 2020
@chitgoks
Copy link

chitgoks commented Jun 25, 2020

hi. can you please share your code how? we probably ended up here and used the same strategy with regards to csrf and jwt token. i got it to work in android but res.headers returns no set-cookie in flutter web.

my problem is that there is no set-cookie when the response.headers is even printed out after login. but in android and in postman, there is a set-cookie there.

@bb-renittojose
Copy link

I ended up using 'dart:html' to read browser cookies.

can you please share the code snippet for that? I tried to read like following but the response was empty. Able to see the set-cookie value in my chrome network tab.

import 'dart:html';
var cookies = document.cookie;
 var cookies = html.window.document.cookie;
        log('Cookie Data: $cookies');

@Luro02
Copy link

Luro02 commented Mar 5, 2024

In case someone else is searching for a solution:

Using dart:html is suboptimal, because then it will not work with non-web platforms like android. Instead add the universal_html dependency and then one can read cookies with:

import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:universal_html/html.dart' show document;

String? readWebCookie(String name) {
  if (!kIsWeb) {
    return null;
  }

  String cookies = document.cookie ?? "";
  for (String value in cookies.isNotEmpty ? cookies.split(";") : []) {
    List<String> map = value.split("=");
    String key = map[0].trim();
    if (name == key) {
      return map[1].trim();
    }
  }

  return null;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants