You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Webview中Set-Cookie响应头获取及Cookie策略配置问题

问题原因

Set-Cookie属于W3C规定的禁止前端JavaScript访问的响应头列表,属于浏览器安全策略限制,因此你通过注入JS重写XHR的方式无论如何都无法获取该字段。

解决方案

一、保证WebView内Set-Cookie正常生效

补全WebView配置即可实现Cookie自动写入、生效:

  • 已开启的sharedCookiesEnabled配置无需修改,该配置用于同步RN层和WebView层的系统Cookie
  • 新增domStorageEnabled={true}配置,开启DOM存储,保证Cookie可以正常持久化
  • 新增thirdPartyCookiesEnabled={true}配置,允许第三方Cookie写入,适配本地file页面请求跨域接口的Cookie写入场景
  • 如果你使用的接口是HTTP协议,Android端需要在AndroidManifest.xml中配置android:usesCleartextTraffic="true",避免Android 9及以上版本拦截HTTP请求导致Cookie写入失败

二、手动获取WebView内请求的Set-Cookie响应头

无需注入JS拦截请求,直接使用react-native-webview提供的onResponseReceived回调即可,该回调会在WebView发起的每一个网络请求收到响应时触发,由原生层直接返回完整的响应头信息,包含Set-Cookie字段。

修改后的完整代码如下:

import React from 'react';
import {Platform, StyleSheet, View} from 'react-native';
import {WebView} from 'react-native-webview';

type WrapperProps = {
  path: string;
};

function Wrapper({path}: WrapperProps) {
  return (
    <View style={styles.container}>
      <WebView
        allowFileAccess
        allowUniversalAccessFromFileURLs
        allowingReadAccessToURL={path}
        javaScriptEnabled
        originWhitelist={['*']}
        sharedCookiesEnabled
        // 新增配置保证Cookie正常生效
        domStorageEnabled={true}
        thirdPartyCookiesEnabled={true}
        source={{
          uri:
            Platform.OS === 'ios'
              ? `file://${path}/index.html`
              : `${path}/index.html`,
        }}
        injectedJavaScript={`(function () {
          // 修正原代码笔误coookie为cookie
          window.ReactNativeWebView.postMessage(JSON.stringify(document.cookie));
        })();
        `}
        onMessage={e => {
          console.log({onMessageEvent: e.nativeEvent.data});
        }}
        // 新增响应监听回调获取Set-Cookie
        onResponseReceived={({ nativeEvent }) => {
          const { responseHeaders, url } = nativeEvent;
          // 可根据url过滤需要获取Cookie的目标业务请求
          if (responseHeaders['Set-Cookie']) {
            const setCookies = responseHeaders['Set-Cookie'];
            // 多Set-Cookie时返回数组,单条时返回字符串,可自行统一格式处理
            console.log('获取到的Set-Cookie:', setCookies);
            // 后续可自行处理Cookie,比如存储到RN侧、同步到其他请求等
          }
        }}
        style={styles.webview}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  webview: {
    height: '100%',
    width: '100%',
  },
});

export default React.memo(Wrapper);

注意事项

  • 需确保你使用的react-native-webview版本 >= 10.9.0,低于该版本无onResponseReceived属性,升级版本后即可正常使用
  • 如果你需要把获取到的Cookie主动同步到WebView,可使用@react-native-cookies/cookies库操作系统Cookie库,开启sharedCookiesEnabled后系统Cookie库的变更会自动同步到WebView中

内容的提问来源于stack exchange,提问作者joseglego

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 08:54:01