This commit is contained in:
zh
2025-12-03 11:03:18 +08:00
8 changed files with 174 additions and 62 deletions

View File

@ -1,4 +1,4 @@
import { app, shell, BrowserWindow, ipcMain, globalShortcut, dialog } from 'electron'
import { app, shell, BrowserWindow, ipcMain, globalShortcut, dialog, session } from 'electron'
import path, { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/earth.png?asset'
@ -390,19 +390,87 @@ function createWindow(): void {
let _winMap = new Map();
// 监听渲染进程创建新窗口的请求
function createTempSession() {
// 生成唯一会话名称(避免冲突)
const sessionName = `temp-session-${Date.now()}-${Math.random().toString(36).slice(2)}`;
// 创建独立会话(基于默认分区,但命名唯一)
const tempSession = session.fromPartition(sessionName, {
cache: true, // 允许缓存,但会话独立
persistent: false // 非持久化,关闭后自动清理
});
// 清空会话初始缓存(确保无残留)
tempSession.clearStorageData({
storages: [
'appcache', 'cookies', 'localstorage', 'sessionstorage',
'indexdb', 'cachestorage', 'websql'
]
}).catch(err => console.error('清空临时会话缓存失败:', err));
return tempSession;
}
// @ts-ignore
ipcMain.handle('create-new-window', async (event, params, url, option, id) => {
// try {
// console.log('create-new-window', params, url, option, id)
// const newWindow = await new BrowserWindow(params)
// if (url) {
// await newWindow.loadURL(url)
// await newWindow.webContents.send("data", option)
// newWindow.on('closed', () => {
// _winMap.delete(id);
// // a.delete(newWindow.id)
// // closeCB(newWindow.id)
// });
// }
// _winMap.set(id, newWindow.id);
// return _winMap
// } catch (error) {
// console.error('创建窗口失败:', error);
// throw error; // 抛出错误以便渲染进程捕获
// }
try {
const newWindow = await new BrowserWindow(params)
// 1. 创建独立临时会话
const tempSession = createTempSession();
// 2. 合并窗口配置:注入独立会话
const windowConfig = {
...params,
webPreferences: {
...params.webPreferences,
session: tempSession, // 关键:使用独立会话
nodeIntegration: true,
contextIsolation: false,
devTools: true,
webSecurity: false,
allowRunningInsecureContent: true
}
};
// 3. 创建新窗口
const newWindow = new BrowserWindow(windowConfig);
// 4. 加载URL并发送初始化数据
if (url) {
await newWindow.loadURL(url)
await newWindow.webContents.send("data", option)
newWindow.on('closed', () => {
_winMap.delete(id);
// a.delete(newWindow.id)
// closeCB(newWindow.id)
});
await newWindow.loadURL(url);
await newWindow.webContents.send("data", option);
}
// 5. 窗口关闭时清理会话和映射
newWindow.on('closed', async () => {
_winMap.delete(id);
// 清空会话缓存并销毁
await tempSession.clearStorageData({
storages: ['all'] // 清空所有存储
});
// 解除会话引用触发GC
tempSession.clearCache();
session.removePartition(tempSession.getPartition());
});
// 6. 记录窗口映射
newWindow.webContents.on('before-input-event', (event, input) => {
// 条件:仅按了 Alt 键(无其他键组合、不是组合键、不是重复按键)
if (
@ -417,7 +485,8 @@ function createWindow(): void {
}
});
_winMap.set(id, newWindow.id);
return _winMap
return _winMap;
} catch (error) {
console.error('创建窗口失败:', error);
throw error; // 抛出错误以便渲染进程捕获