首页 > 解决方案 > 关闭 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.commysite.com/my-profilewhere页面,它也可以工作。/my-profile我的标头仅适用于第一个请求页面。如何解决?关闭每个页面的应用程序后如何保存会话,而不仅仅是域值?

标签: react-nativesessioncookieswebviewheader

解决方案


推荐阅读