I have done a sign in to my app using the native fetch API. I now need to load an image, so am loading it in a <WebView>
, however the webview is not using the cookies from the fetch API outside of the webview. Is it possible to tell webview to use those cookies?
2 Answers
You can post a message containing your cookies content to your Webview using postMessage().
You need to get the ref of the Webview then post the message to your webview.
let webviewRef = null;
const cookiesContent = 'My cookies bla bla bla'
render() {
return (
<WebView
onLoad={() => webviewRef.postMessage(cookiesContent)}
ref={webview => { webviewRef = webview; }}
source={{ uri: 'https://YourUrl' }}
/>
);
}
Then in your Website you can create the cookies and use it
<script>
document.addEventListener("message", function(data) {
document.cookie=`cookiesName=${data.data}`;
});
</script>
If you aren't the owner of the website you can still try to inject the javascript with injectedJavaScript props of Webview Component.
const JsCode = 'document.addEventListener("message", function(data) {
document.cookie=`cookiesName=${data.data}`;
});';
<WebView
injectedJavaScript={JsCode}
onLoad={() => webviewRef.postMessage(cookiesContent)}
ref={webview => { webviewRef = webview; }}
source={{ uri: 'https://YourUrl' }}
/>
-
2This is superb thank you @Gabriel - how can I get the stored cookies from the fetch API? Is making a dummy request and getting the headers the only way? Nov 17, 2017 at 2:39
You can use https://github.com/react-native-community/cookies to get cookies and set them back
image-rendering: pixelated;