session 模块是 Electron 中的一个模块,用于管理浏览器会话。每个 Electron 的 BrowserWindow 实例都有一个关联的会话(session),可以通过 webContents 对象的 session 属性来访问。

session 模块允许你对会话进行配置,例如设置代理、清除缓存、管理 cookie 等。以下是一些 session 模块的用法示例:

1. 获取默认会话:
   const { session } = require('electron');
   const defaultSession = session.defaultSession;

2. 创建自定义会话:
   const { app, session } = require('electron');

   // 创建自定义会话
   const customSession = session.fromPartition('custom');

   // 使用自定义会话加载页面
   const mainWindow = new BrowserWindow({ width: 800, height: 600, webContents: { session: customSession } });
   mainWindow.loadURL('https://example.com');

3. 会话配置示例:
   const { app, session } = require('electron');

   // 获取默认会话
   const defaultSession = session.defaultSession;

   // 设置代理
   defaultSession.setProxy({ proxyRules: 'http=myproxy:80;https=myproxy:80' });

   // 清除会话缓存
   defaultSession.clearCache(() => {
     console.log('Cache cleared!');
   });

   // 监听 Cookie 改变事件
   defaultSession.cookies.on('changed', (event, cookie, cause, removed) => {
     console.log('Cookie changed:', cookie);
   });

4. 在 webContents 中使用自定义会话:
   const { session } = require('electron');

   const customSession = session.fromPartition('custom');

   const mainWindow = new BrowserWindow({ width: 800, height: 600 });

   // 在 webContents 中使用自定义会话
   mainWindow.webContents.session = customSession;

这些只是 session 模块的一些基本用法示例。你可以根据应用的需求,使用 session 模块进行更详细的配置和管理,例如设置代理、设置请求过滤器、管理 Cookie、拦截网络请求等。


转载请注明出处:http://www.pingtaimeng.com/article/detail/10927/Electron