React Native에서 WebView 쿠키 관리하기
안됐던 모듈
- react-cookies
- react-native-cookies
- 이 모듈은 개발중단 됐고, react-native-community로 이전됐음.
사용 가능 모듈
1. RN에서 쿠키설정하고 웹뷰와 공유하기
React Native에서 @react-native-community/cookies 패키지로 쿠키 설정 가능.
- It’s a cookie management library for React Native and lets you manage cookies natively.
⇒ 이걸 웹뷰의 쿠키로 설정하고 싶으면
WebView
컴포넌트에서 sharedCookiesEnabled
prop 켜주면 됨.# 설치 $ yarn add @react-native-community/cookies #패키지 추가 $ npx pod-install #ios 링킹
import CookieManager from '@react-native-community/cookies'; ... CookieManager.set('http://192.168.25.31:3000', { name:'cardinal', value:'5' }) .then((done)=>console.log("cookiemanager success", done)) //true or false .catch((err)=>console.log("cookiemanager error : ", err))
const App = () => { return( <WebView source={{ uri: 'http://www.naver.com' }} sharedCookiesEnabled={true} /> ) }
2. WebView에 커스텀 쿠키 지정해서 설정하기
잘 안됐음. 그냥 @react-native-community/cookies 써라
- 웹뷰에 직접적으로 커스텀 헤더 설정
- 주의 : 이렇게 하면 첫 번째 로드에서는 헤더가 설정되지만 이후 페이지 탐색에서는 설정되지 않는다.
- 각 페이지가 로드될 때마다 커스텀 헤더를 설정해야함.
- 자세한 내용은 링크에서 확인
const App = () => { return ( <WebView source={{ uri: 'http://example.com', headers: { Cookie: 'cookie1=asdf; cookie2=dfasdfdas', }, }} sharedCookiesEnabled={true} /> ); };
다른 페이지로 이동하더라도 헤더를 그대로 유지하도록 만들기
예시1
class testApp extends Component { state = { url: "http://localhost:3000", }; render() { return ( <WebView onLoadStart={(navState) => //현재 uri와 동일하게 유지되는 상태값을 두어, 값이 바뀌면 re-render 되는 원리로 마치 첫 페이지를 로드하는 것처럼 커스텀 헤더값이 계속 설정되어 유지됨. this.setState({ url: navState.nativeEvent.url }) } source={{ uri: this.state.url, headers: { "custom-app-header": "react-native-ios-app" }, }} /> ); } }
예시2
const CustomHeaderWebView = (props) => { const { uri, onLoadStart, ...restProps } = props; //현재 uri와 동일하게 유지되는 상태값을 두어, 값이 바뀌면 re-render 되는 원리로 마치 첫 페이지를 로드하는 것처럼 커스텀 헤더값이 계속 설정되어 유지됨. const [currentURI, setURI] = useState(props.source.uri); const newSource = { ...props.source, uri: currentURI }; return ( <WebView {...restProps} source={newSource} onShouldStartLoadWithRequest={(request) => { // If we're loading the current URI, allow it to load if (request.url === currentURI) return true; // We're loading a new URL -- change state first setURI(request.url); return false; }} /> ); }; <CustomHeaderWebView source={{ uri: 'http://example.com', headers: { Cookie: 'cookie1=asdf; cookie2=dfasdfdas', }, }} />;