WebView should use same cookies as fetch

Viewed 2787

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' }}
    />
Related