如何在反应电子应用程序中使用 cookie?

5 reactjs electron

我正在尝试在我的电子反应应用程序中使用 cookie。
目前我完全无法让它工作。
需要电子或在反应组件中导入它会抛出“TypeError: fs.existsSync is not a function”。
中断的示例代码(App.js例如):

import { WebContent } from 'electron';
Run Code Online (Sandbox Code Playgroud)

或者

const { session } = require('electron');
Run Code Online (Sandbox Code Playgroud)

我要做的是Main.js文件中的以下代码:

const { app, BrowserWindow, session } = require('electron');

session.defaultSession.cookies.get({}).then(cookies => {
    console.log(cookies)
});
Run Code Online (Sandbox Code Playgroud)

我按照这个教程将 Electron 与 React 结合使用:基础知识来设置我的电子React应用程序。

我也跟着this answer to a similar question但是当我这样做时:

const { session } = window.require('electron');
console.log(session.defaultSession.cookies);
Run Code Online (Sandbox Code Playgroud)

它说会话未定义。

Pet*_*rdt 1

我猜想,您想在渲染器进程(用于渲染 UI 的 js 文件)中使用 cookie。由于 cookie 通常只能在主进程中访问,并且自 Electron 版本 10 以来默认关闭“远程”访问,因此必须通过在创建浏览器窗口时设置(主进程)enableRemoteModule: true来再次打开它。main.js对我来说这看起来像那样

const mainWindow = new BrowserWindow({
  width: 800,
  height: 600,
  webPreferences: {
    nodeIntegration: true,
    enableRemoteModule: true,
  }
});
Run Code Online (Sandbox Code Playgroud)

(另外,nodeIntegration: true在我的情况下是必要的,但在您的情况下可能不是为了防止process未定义的错误。)

设置该值后,您只需执行以下操作即可访问会话对象

import electron from 'electron';
const {remote} = electron;
const {session} = remote;

console.log(session.defaultSession.cookies);
Run Code Online (Sandbox Code Playgroud)

在你的渲染器代码中。此外,您还可以通过 访问通常只能在主进程中访问的所有其他对象electron.remote。干杯。