Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yasserzubair/bd7e9017ad91792bb1dc81a69ad89967 to your computer and use it in GitHub Desktop.
Save yasserzubair/bd7e9017ad91792bb1dc81a69ad89967 to your computer and use it in GitHub Desktop.
React Native Trick: Get Cookies of WebView without using any native modules such as react-native-cookies. Might be helpful for getting JWT while making OAuth2 👽
// @flow
import React, { Component } from 'react';
import {
WebView,
} from 'react-native';
class LoginScreen extends Component {
state = {
cookies : {},
webViewUrl : ''
}
onNavigationStateChange = (webViewState: { url: string }) => {
const { url } = webViewState;
// when WebView.onMessage called, there is not-http(s) url
if(url.includes('http')) {
this.setState({ webViewUrl: url })
}
}
_checkNeededCookies = () => {
const { cookies, webViewUrl } = this.state;
if (webViewUrl === 'SUCCESS_URL') {
if (cookies['cookie-name-for-jwt']) {
alert(cookies['cookie-name-for-jwt']);
// do your magic...
}
}
}
_onMessage = (event) => {
const { data } = event.nativeEvent;
const cookies = data.split(';'); // `csrftoken=...; rur=...; mid=...; somethingelse=...`
cookies.forEach((cookie) => {
const c = cookie.trim().split('=');
const new_cookies = this.state.cookies;
new_cookies[c[0]] = c[1];
this.setState({ cookies: new_cookies });
});
this._checkNeededCookies();
}
render() {
const jsCode = "window.postMessage(document.cookie)"
// let jsCode = "window.postMessage(document.cookie= 'login=; expires=Bla bla bla')"; // if you need to write some cookies, not sure if it goes to shared cookies, most probably no :)
return (
<WebView
source={{ uri: 'AUTH_URL' }}
onNavigationStateChange={this.onNavigationStateChange}
onMessage={this._onMessage}
injectedJavaScript={jsCode}
style={{ flex: 1 }}
/>
);
}
}
export default LoginScreen;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment