WebView should use same cookies as fetch

。_饼干妹妹 提交于 2019-12-10 16:52:59

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/47340210/webview-should-use-same-cookies-as-fetch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!