react-native - 关闭 IOS 应用程序后的 react-native WebView 会话
问题描述
我有一个带有 WebView 组件的简单反应原生应用程序,用于显示基于 php 的网站。所以它有效。但是,当我登录并关闭应用程序(在 IOS 上)时,会话状态很松散,我需要再次登录。我知道当应用程序关闭时,所有 webview 数据(如 cookie)都会被清除。所以我需要 AsyncStorage 将所有 cookie 保存到应用程序存储中,并在应用程序打开时获取它以传递给标头。
这是我的代码:
import React, {Component} from 'react';
import AsyncStorage from '@react-native-community/async-storage';
import CookieManager from '@react-native-community/cookies';
import {SafeAreaView, StyleSheet, Alert} from 'react-native';
import {WebView} from 'react-native-webview';
let domain = "[https]://mysite.com";
export default class WebViewScreen extends Component {
constructor(props) {
super(props);
this.currentUrl = domain;
this.myWebView = React.createRef();
this.state = {
isReady: false,
cookiesString: '',
};
}
jsonCookiesToCookieString = (json) => {
let cookiesString = '';
for (let [key, value] of Object.entries(json)) {
cookiesString += `${key}=${value.value}; `;
}
return cookiesString;
};
UNSAFE_componentWillMount() {
this.provideMeSavedCookies()
.then(async (savedCookies) => {
let cookiesString = this.jsonCookiesToCookieString(savedCookies);
const PHPSESSID = await AsyncStorage.getItem('PHPSESSID');
if (PHPSESSID) {
cookiesString += `PHPSESSID=${PHPSESSID};`;
}
this.setState({cookiesString, isReady: true});
})
.catch((e) => {
this.setState({isReady: true});
});
}
onLoadEnd = (syntheticEvent) => {
let successUrl = `${domain}/dashboard.php`;
if (this.currentUrl === successUrl) {
CookieManager.getAll(true).then((res) => {
AsyncStorage.setItem('savedCookies', JSON.stringify(res));
if (res.PHPSESSID) {
AsyncStorage.setItem('PHPSESSID', res.PHPSESSID.value);
}
});
}
};
onNavigationStateChange = (navState) => {
this.currentUrl = navState.url;
};
provideMeSavedCookies = async () => {
try {
let value = await AsyncStorage.getItem('savedCookies');
if (value !== null) {
return Promise.resolve(JSON.parse(value));
}
} catch (error) {
return {}
}
};
render() {
const {cookiesString, isReady} = this.state;
if (!isReady) {
return null;
}
return (
<SafeAreaView>
<WebView
ref={this.myWebView}
source={{
uri: domain,
headers: {
Cookie: cookiesString,
},
}}
allowsBackForwardNavigationGestures
originWhitelist={['*']}
scalesPageToFit
useWebKit
onLoadEnd={this.onLoadEnd}
onNavigationStateChange={this.onNavigationStateChange}
sharedCookiesEnabled={true}
javaScriptEnabled={true}
domStorageEnabled={true}
/>
</SafeAreaView>
);
}
}
我错过了所有最清楚和理解代码的样式
所以,我登录并关闭应用程序。然后再次打开。它仅适用于一个请求,但不适用于多个请求或导航时。当我尝试转到另一个页面时,我失去了会话并重定向到登录页面。如果我仅将域变量从授权用户更改mysite.com
为mysite.com/my-profile
where页面,它也可以工作。/my-profile
我的标头仅适用于第一个请求页面。如何解决?关闭每个页面的应用程序后如何保存会话,而不仅仅是域值?
解决方案
推荐阅读
- python - 如何从 github 安装存储库?
- c# - Task.Run 仍然冻结 UI
- variables - 如何使用变量作为不同变量的数据类型?
- r - R 包 twitteR 中的推文函数之间无法解释的差异
- html - 正则表达式排除与负前瞻匹配的所有组
- laravel - 获取时无法更新函数内部的 vue 数据?
- regex - pgbadger 匹配 RDS 日志的正确模式是什么?
- python - 如何让创建语句尊重自定义 Django 字段中的“from_db_value”?
- google-cloud-platform - 使用 AutoML 对象检测接收到的 JSON 负载无效
- java - CountDownTimer 为每个循环增加时间