reb*_*lok 5 react-native react-native-ios react-native-webview react-native-cookies
我有一个在 web 视图中打开的单点登录网站。用户登录后,我需要使用 cookie 来从 API 请求令牌,并在应用程序中将其用于所有其他请求。这一切在 Android 上运行良好,但在 iOS 上,当我请求令牌时,没有 cookie。WebView 配置为使用共享 cookie 存储:
<WebView
source={{ uri: loginUrl }}
onMessage={handleSsoLogin}
injectedJavaScriptBeforeContentLoaded={JS_INTERFACE}
sharedCookiesEnabled={true}
/>
Run Code Online (Sandbox Code Playgroud)
如果我使用 devTools 检查 webView,我可以看到 cookie。另外,如果我再次访问 SSO 站点,我已经记录了它。因此,cookie 被 webView 保存和使用。它们只是不被使用fetch并且 CookieManager 不访问它们:
const cookies = await CookieManager.get(url);
console.log({ cookies });
...
{"cookies": {}}
Run Code Online (Sandbox Code Playgroud)
那么,问题来了,如何从webView中获取这些cookie呢?
小智 9
您需要使用 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);
});
}
});
}
};Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15826 次 |
| 最近记录: |