【问题标题】:How can I get cookies from react native webView on iOS?如何从 iOS 上的 react native webView 获取 cookie?
【发布时间】:2020-07-30 07:59:32
【问题描述】:

我在 webView 中打开了一个单点登录网站。用户登录后,我需要获取一个 cookie 来从 API 请求一个令牌,并在应用程序中使用它来处理所有其他请求。 这一切都在 Android 上运行良好,但是当我请求令牌时,iOS 没有 cookie。 WebView 配置为使用共享 cookie 存储:

    <WebView
        source={{ uri: loginUrl }}
        onMessage={handleSsoLogin}
        injectedJavaScriptBeforeContentLoaded={JS_INTERFACE}
        sharedCookiesEnabled={true}
      />

如果我使用 devTools 检查 webView,我可以看到 cookie。另外,如果我再次访问 SSO 站点,我已经登录了它。因此,cookie 被 webView 持久化和使用。 fetch 没有使用它们,CookieManager 也没有访问它们:

const cookies = await CookieManager.get(url);
console.log({ cookies });
...
{"cookies": {}}

那么,问题是,如何从 webView 中获取这些 cookie?

【问题讨论】:

    标签: react-native react-native-ios react-native-webview react-native-cookies


    【解决方案1】:

    你需要使用 import CookieManager from "@react-native-community/cookies";

    在 webview 中,你可以这样做:

     <WebView
              cacheEnabled={false}
              ref={ref => (this.webView = ref)}
              source={{
                uri: "http://yoururl.com"
              }}
              style={{ marginTop: 20 }}
              onNavigationStateChange={this.navChange}
              thirdPartyCookiesEnabled={true}
            />
            {this.state.loading && (
              <ActivityIndicator
                color={"blue"}
                style={{ flex: 20 }}
                size={"large"}
              />
              
              
    navChange = e => {
        console.log("e", e);
        this.setState({ loading: e.loading });
        if (e.url == "http://yoururl.com/landing") {
          CookieManager.getAll(true).then(res => {
            console.log("CookieManager.getAll =>", res);
            if (!!res) {
              console.log({res})
              CookieManager.clearAll(true).then(res => {
                console.log("LoginScreen CookieManager.clearAll =>", res);
              });
            }
          });
        }
      };

    【讨论】:

    • 我在使用 CookieManager,但我是这样使用它的:const cookies = await CookieManager.get(url); 它确实返回了任何东西,但是您使用 CookieManager.getAll(true) 的建议奏效了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2017-04-07
    • 2018-02-05
    相关资源
    最近更新 更多