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

如何让Tauri构建版应用正常设置Cookie?仅开发模式生效

解决Tauri构建版无法设置Cookie的问题

核心原因

开发模式下Tauri使用http://localhost服务,属于HTTP协议,默认允许Cookie操作;但构建后应用使用Tauri自定义协议或file://协议,默认安全策略限制了Cookie设置,导致js-cookie失效。

方案一:改用Tauri本地存储(推荐,无需懂Rust)

桌面应用更适合用本地存储替代Cookie,Tauri官方提供了tauri-plugin-store插件,操作简单:

  • 安装插件:
    npm install @tauri-apps/plugin-store
    
  • 在React组件中使用:
    import { Store } from '@tauri-apps/plugin-store';
    
    // 创建存储实例(文件名自定义,会存在应用数据目录)
    const store = new Store('.app-settings.dat');
    
    // 保存数据(替代Cookie.set)
    const saveData = async (name, value) => {
      await store.set(name, value);
      await store.save(); // 必须调用save完成持久化
    };
    
    // 获取数据(替代Cookie.get)
    const getData = async (name) => {
      return await store.get(name);
    };
    

方案二:开启Cookie支持(需少量Rust代码,复制粘贴即可)

如果必须使用Cookie,按以下步骤修改:

  1. 修改tauri.conf.json:
    在security节点添加Cookie配置:
    {
      "tauri": {
        "security": {
          "cookies": {
            "allowFileProtocol": true
          },
          // 保留原有其他配置
        }
      }
    }
    
  2. 修改src-tauri/src/main.rs:
    复制以下代码替换原有内容(仅添加必要的Cookie启用代码):
    use tauri::Manager;
    
    fn main() {
      tauri::Builder::default()
        .setup(|app| {
          // 启用WebView的Cookie支持
          app.webview().unwrap().enable_cookies();
          Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
    }
    
    完成后重新构建应用,js-cookie即可正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 00:27:16