flutter 플러그인 웹뷰flutter의 쿠키 관리

3072 단어 flutterwebview
1.set-cookies
  set cookie  ,         set cookie,            、       cookie  , clear cookie,  set cookie
setSessionID() async {
  String sessionID = await LocalStorage.get("sessionID");
  if (Platform.isIOS) {
    _controller.evaluateJavascript("document.cookie = 'sessionID=${sessionID}'").then((res) {
      print("webViewController.evaluateJavascript========>${res}");
      _onListCookies(_controller, context);
    });
  } else {
    _controller.evaluateJavascript('document.cookie = "sessionID=${sessionID};"').then((res) {
      print("webViewController.evaluateJavascript========>${res}");
      _onListCookies(_controller, context);
    });
  }
}

2.get-cookies
void _onListCookies(WebViewController controller, BuildContext context) async {
  final String cookies = await controller.evaluateJavascript('document.cookie');
  print("cookies=========>${cookies}");
  var cookieValue = NetworkService.getCookieRowValByName(cookies, Config.CUSTOMERNO);
  print("cookies-CUSTOMERNO=========>${cookieValue}");
}

3.clear-cookies
final CookieManager cookieManager = CookieManager();
void _onClearCookies() async {
  final bool hadCookies = await cookieManager.clearCookies();
  String message = 'There were cookies. Now, they are gone!';
  if (!hadCookies) {
    message = 'There are no cookies.';
  }
  print(message);
}

4.get-cookie-by-cookie-name-from-cookie-row
static String getCookieRowValByName(String cookieRow, String cookieName) {
  var cookies = cookieRow.split(';');
  var cookieValue = "";
  for (var rawCookie in cookies) {
    if (rawCookie.length > 0) {
      var keyValue = rawCookie.split('=');
      if (keyValue.length == 2) {
        var key = keyValue[0].trim();
        var value = keyValue[1];

        if (key == cookieName)
          cookieValue = value;
      }
    }
  }
  return cookieValue;
}

5.get-cookie-by-name-from-response
static String getCookieByName(ResultData response, String cookieName) {
  List setCookies = response.headers['set-cookie'];
  String cookieValue = "";
  if (setCookies != null) {

    for (var setCookie in setCookies) {
      var cookies = setCookie.split(';');

      for (var rawCookie in cookies) {
        if (rawCookie.length > 0) {
          var keyValue = rawCookie.split('=');
          if (keyValue.length == 2) {
            var key = keyValue[0].trim();
            var value = keyValue[1];

            if (key == cookieName)
              cookieValue = value;
          }
        }
      }
    }
  }
  return cookieValue;
}

웹뷰와 js 상호 조정 참조 문서:https://imnerd.org/ios-webview-and-js.html
webview_flutter 관련 api:http://www.coderzheaven.com/2019/03/28/webview-in-flutter-part-2/

좋은 웹페이지 즐겨찾기