flutter插件webview_flutter的cookies管理

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;
}

webview与js互调参考文档:https://imnerd.org/ios-webview-and-js.html

webview_flutter相关api:  http://www.coderzheaven.com/2019/03/28/webview-in-flutter-part-2/

你可能感兴趣的:(flutter,webview)