如何修复IOS端React Native WebView关应用后会话仅首请求生效问题
问题原因
你当前的实现仅将Cookie注入了首次请求的请求头,WebView内部跳转发起的后续请求不会继承该请求头,因此只有初始页面能识别会话,跳转后就会丢失身份状态。
修复方案
核心思路:不要仅在首次请求头加Cookie,而是提前将存储的Cookie写入iOS WebKit的全局Cookie存储,这样同域名下所有请求都会自动携带Cookie,不需要手动拼请求头。
具体修改步骤如下:
- 替换原来的Cookie拼请求头逻辑,改为通过
@react-native-community/cookies的set方法批量写入Cookie - 移除WebView source中的Cookie请求头配置
- 优化Cookie存储逻辑,避免漏存更新后的Cookie
核心代码修改
1. 替换旧的生命周期逻辑
建议将不安全的UNSAFE_componentWillMount替换为componentDidMount,逻辑改为写入Cookie:
componentDidMount() { this.provideMeSavedCookies() .then(async (savedCookies) => { // 批量写入存储的所有Cookie到WebKit全局存储 const cookiePromises = Object.entries(savedCookies).map(([key, cookieItem]) => { return CookieManager.set(domain, { name: key, value: cookieItem.value, path: cookieItem.path || '/', secure: cookieItem.secure || false, httpOnly: cookieItem.httpOnly || false, domain: cookieItem.domain || 'mysite.com' // 和后端设置Cookie的domain保持一致 }, true); // 第二个参数true对应你开启的useWebKit模式 }) // 额外写入单独存储的PHPSESSID const PHPSESSID = await AsyncStorage.getItem('PHPSESSID'); if (PHPSESSID) { cookiePromises.push(CookieManager.set(domain, { name: 'PHPSESSID', value: PHPSESSID, path: '/', secure: true, // 如果你是HTTPS站点请设为true domain: 'mysite.com' }, true)) } // 所有Cookie写入完成后再加载WebView await Promise.all(cookiePromises); this.setState({isReady: true}); }) .catch((e) => { this.setState({isReady: true}); }); }
2. 修改WebView配置
移除source中手动注入的Cookie请求头:
<WebView ref={this.myWebView} source={{ uri: domain }} // 移除原来的headers配置 allowsBackForwardNavigationGestures originWhitelist={['*']} scalesPageToFit useWebKit onLoadEnd={this.onLoadEnd} onNavigationStateChange={this.onNavigationStateChange} sharedCookiesEnabled={true} javaScriptEnabled={true} domStorageEnabled={true} />
3. 优化Cookie存储逻辑
原逻辑仅在跳转到dashboard.php时才存储Cookie,建议调整为每次加载完成都同步,避免会话中途更新后没有同步到本地:
onLoadEnd = (syntheticEvent) => { CookieManager.getAll(true).then((res) => { AsyncStorage.setItem('savedCookies', JSON.stringify(res)); if (res.PHPSESSID) { AsyncStorage.setItem('PHPSESSID', res.PHPSESSID.value); } }); };
内容的提问来源于stack exchange,提问作者Eugene Zhutnik
相关产品推荐
相关产品推荐

