react-native - WebView 应该使用与 fetch 相同的 cookie

标签 react-native react-native-android

我已经使用 native fetch API 登录了我的应用程序。我现在需要加载图像,所以将其加载到 <WebView> ,但是 webview 没有使用 webview 之外的 fetch API 中的 cookie。是否可以告诉 webview 使用这些 cookie?

最佳答案

您可以使用 postMessage() 将包含您的 cookie 内容的消息发布到您的 Webview。

您需要获取 Webview 的 ref,然后将消息发布到您的 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' }}
        />
    );
}

然后在您的网站中,您可以创建 cookie 并使用它
<script>
    document.addEventListener("message", function(data) {
        document.cookie=`cookiesName=${data.data}`;
    });
</script>

如果您不是该网站的所有者,您仍然可以尝试使用 Webview 组件的注入(inject) JavaScript Prop 注入(inject) javascript。
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' }}
    />

关于react-native - WebView 应该使用与 fetch 相同的 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47340210/

相关文章:

React-native 0.60 - Android 构建发布失败 - OutOfMemory

react-native - 如果页面 protected 并且用户未登录,如何重定向到登录?

React-Native:布局动画

react-native - com.android.builder.testing.api.DeviceException : com. android.ddmlib.InstallException: INSTALL_FAILED_DEXOPT

react-native - undefined不是对象(评估 'allRowsIDs.length')(React-Native)

react-native - AsyncStorage是永久性的还是临时性的?

android - 处理 React Native 中的后退按钮,Android 上的 Navigator

android - 如何在 native react 中对 TextInput 应用点击事件

javascript - 在 render() 之前加载图像

react-native - TextInput的内容不是垂直居中