I have a webapp that's already production ready to run inside a React Native Webview. The app uses the package js-cookie which saves the accessToken and refreshToken to the browser cookies.
import Cookies from 'js-cookie';
import { LoginTokens } from '@/types/auth';
export const saveTokensToCookies = (loginTokens: LoginTokens) => {
...
Cookies.set('accessToken', loginTokens.accessToken, {
expires: expiresAt,
});
}
export const getTokenFromCookies = (token: string): string | undefined => {
if (token === TokenTypes.ACCESS_TOKEN) {
return Cookies.get(TokenTypes.ACCESS_TOKEN);
}
if (token === TokenTypes.REFRESH_TOKEN) {
return Cookies.get(TokenTypes.REFRESH_TOKEN);
}
return undefined;
};
If I log the value from getTokenFromCookies from my react app it works without any issues.
However when I try to access these values from the webview, it doesnt seem to be saved to the browser cookies. Though I do understand that webview is not ran inside a browser, I would like to know any alternate ways on how to approach this? I need to be able to at least log-in on my react app from my webview but since it relies on browser cookies it presents a challenge. Below is how I am able to check cookies from my react native app.
const CHECK_COOKIE: string = `
ReactNativeWebView.postMessage("Cookie: " + document.cookie);
true;
`;
const onNavigationStateChange = (navigationState: WebViewNavigation) => {
if (webviewRef.current) {
webviewRef.current.injectJavaScript(CHECK_COOKIE);
} else {
console.log('no webview');
}
};
const onMessage = (event) => {
const { data } = event.nativeEvent;
console.log(data);
};
return (
<View className="absolute inset-0 z-10 bg-white pt-14">
<Menu canGoBack onBack={handleLogout} />
<SafeAreaView style={{ flex: 1 }}>
<WebView
ref={webviewRef}
source={{ uri: accessUrl }}
onNavigationStateChange={onNavigationStateChange}
onMessage={onMessage}
originWhitelist={['*']}
sharedCookiesEnabled
thirdPartyCookiesEnabled
javaScriptEnabled
/>
</SafeAreaView>
</Menu>
</View>
)
After logging in I dont see the accessToken and refreshToken.
How am I able to log in from inside my webview? Any suggestions?
httpor you are loading localfile://url?