修复使用生产模式打包后,调用set-cookie后,document.cookie仍然为空的问题。

This commit is contained in:
Allen 2025-04-30 23:09:05 +08:00
parent 77ef0139fc
commit 950d589f0f
6 changed files with 62 additions and 67 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 628 B

View File

@ -30,8 +30,8 @@ interface ApiResponse<T> {
// 检查登录状态 // 检查登录状态
function checkLoginStatus() { function checkLoginStatus() {
const auth = document.cookie.split('; ').find(row => row.startsWith('EACToken=') || row.startsWith('MssSsoToken=')); const cookie = window.electronAPI.getSessionStorage('cookie');
if (!auth) { if (!cookie) {
window.location.href = 'login.html'; window.location.href = 'login.html';
return; return;
} }
@ -45,7 +45,7 @@ function checkLoginStatus() {
// 处理退出登录 // 处理退出登录
function handleLogout() { function handleLogout() {
document.cookie = 'expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'; window.electronAPI.removeSessionStorage('cookie');
window.location.href = 'login.html'; window.location.href = 'login.html';
} }
@ -53,7 +53,10 @@ function handleLogout() {
async function getMenuList(): Promise<MenuItem[]> { async function getMenuList(): Promise<MenuItem[]> {
try { try {
const response = await fetch('http://1.12.73.211:8848/EIAC_Desktop_Api/api/Menu/GetMenu', { const response = await fetch('http://1.12.73.211:8848/EIAC_Desktop_Api/api/Menu/GetMenu', {
method: 'POST' method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}); });
const result = await response.json() as ApiResponse<MenuItem[]>; const result = await response.json() as ApiResponse<MenuItem[]>;
@ -103,8 +106,7 @@ function createMenuItem(item: MenuItem, menuList: MenuItem[]): HTMLLIElement {
icon.src = item.IconConfig._1x.Selected; icon.src = item.IconConfig._1x.Selected;
const url: string = item.Url.startsWith("http") ? item.Url : `http://${item.Url}`; const url: string = item.Url.startsWith("http") ? item.Url : `http://${item.Url}`;
const result = await window.electronAPI.checkUrlAvailable(url);
const result = await window.electronAPI.checkUrl(url);
if (result.ok && result.status >= 200 && result.status < 400) { if (result.ok && result.status >= 200 && result.status < 400) {
console.log('✅ URL 可访问:', result.status); console.log('✅ URL 可访问:', result.status);
(document.querySelector("webview") as WebviewTag).src = url; (document.querySelector("webview") as WebviewTag).src = url;

View File

@ -19,17 +19,6 @@ interface ApiResponse<T = any> {
data: T; data: T;
} }
// 设置Cookie的示例
const setCookies = async (cookieString: string) => {
try {
await window.electronAPI.setCookie(cookieString);
console.log('Cookies设置成功');
} catch (error) {
console.error('设置Cookies失败:', error);
}
};
// 使用示例 // 使用示例
// setCookies('key1=value1; key2=value2; key3=value3'); // setCookies('key1=value1; key2=value2; key3=value3');
@ -63,7 +52,7 @@ async function handleLogin(account: string, password: string): Promise<void> {
} else { } else {
// 登录成功将data.Cookies拼接为字符串存储cookie // 登录成功将data.Cookies拼接为字符串存储cookie
const cookies = rspBody.data.Cookies.map(cookie => `${cookie.Key.trim()}=${cookie.Value.trim()}`).join('; '); const cookies = rspBody.data.Cookies.map(cookie => `${cookie.Key.trim()}=${cookie.Value.trim()}`).join('; ');
await setCookies(cookies); window.electronAPI.setSessionStorage('cookie', cookies);
// 跳转到主页面 // 跳转到主页面
window.location.href = 'index.html'; window.location.href = 'index.html';
} }

View File

@ -10,18 +10,7 @@ if (started) {
app.quit(); app.quit();
} }
// 处理设置Cookie的IPC请求 ipcMain.handle('check-url-available', async (event, rawUrl: string) => {
ipcMain.handle('set-cookie', async (event, cookie) => {
try {
await event.sender.session.cookies.set(cookie);
return true;
} catch (error) {
console.error('设置Cookie失败:', error);
return false;
}
});
ipcMain.handle('check-url', async (event, rawUrl: string) => {
try { try {
const url = new URL(rawUrl); const url = new URL(rawUrl);
const lib = url.protocol === 'https:' ? https : http; const lib = url.protocol === 'https:' ? https : http;
@ -73,12 +62,34 @@ const createWindow = () => {
nodeIntegration: false, // 禁用 Node.js 集成,提高安全性。 nodeIntegration: false, // 禁用 Node.js 集成,提高安全性。
preload: path.join(__dirname, 'preload.js'), // 预加载脚本 preload: path.join(__dirname, 'preload.js'), // 预加载脚本
webviewTag: true, // 启用webview标签 webviewTag: true, // 启用webview标签
//webSecurity: false, // 禁用web安全策略 //webSecurity: false, // 禁用web安全策略,允许跨域请求
//allowRunningInsecureContent: true, // 允许运行不安全的内容 //allowRunningInsecureContent: true, // 允许运行不安全的内容
//sandbox: false // 禁用沙箱 //sandbox: false // 禁用沙箱
}, },
}); });
// // 配置 webview 的权限
// win.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
// callback({
// requestHeaders: {
// ...details.requestHeaders,
// 'Origin': 'http://1.12.73.211:8848'
// }
// });
// });
// // 配置 webview 的响应头
// win.webContents.session.webRequest.onHeadersReceived((details, callback) => {
// callback({
// responseHeaders: {
// ...details.responseHeaders,
// 'Access-Control-Allow-Origin': ['*'],
// 'Access-Control-Allow-Methods': ['GET, POST, PUT, DELETE, OPTIONS'],
// 'Access-Control-Allow-Headers': ['Content-Type, Authorization']
// }
// });
// });
// 隐藏顶部菜单栏 // 隐藏顶部菜单栏
win.setMenuBarVisibility(false); win.setMenuBarVisibility(false);
win.setAutoHideMenuBar(true); win.setAutoHideMenuBar(true);
@ -134,7 +145,6 @@ const createWindow = () => {
tray.on('click', () => { tray.on('click', () => {
win.show(); win.show();
}); });
}; };
// This method will be called when Electron has finished // This method will be called when Electron has finished

View File

@ -4,35 +4,26 @@
import { contextBridge, ipcRenderer } from 'electron'; import { contextBridge, ipcRenderer } from 'electron';
contextBridge.exposeInMainWorld('electronAPI', { contextBridge.exposeInMainWorld('electronAPI', {
setCookie: async (cookieString: string) => { // 检查URL是否可用
const cookies = cookieString.split(';').map(cookie => { checkUrlAvailable: (url: string) => ipcRenderer.invoke('check-url-available', url),
const [name, value] = cookie.trim().split('=');
return {
name: name.trim(),
value: value.trim(),
path: '/',
secure: false,
httpOnly: false,
expirationDate: Math.floor(Date.now() / 1000) + 86400 // 24小时后过期
};
});
// 为每个域名设置Cookie // 设置 sessionStorage
const domains = ['localhost', '1.12.73.211']; setSessionStorage: (key: string, value: string) => {
const ports = ['', ':8848']; window.sessionStorage.setItem(key, value);
for (const cookie of cookies) {
for (const domain of domains) {
for (const port of ports) {
const url = `http://${domain}${port}`;
await ipcRenderer.invoke('set-cookie', {
...cookie,
url,
domain
});
}
}
}
}, },
checkUrl: (url: string) => ipcRenderer.invoke('check-url', url)
// 获取 sessionStorage
getSessionStorage: (key: string) => {
return window.sessionStorage.getItem(key);
},
// 删除 sessionStorage
removeSessionStorage: (key: string) => {
window.sessionStorage.removeItem(key);
},
// 清空 sessionStorage
clearSessionStorage: () => {
window.sessionStorage.clear();
}
}); });

View File

@ -1,6 +1,9 @@
export interface ElectronAPI { export interface ElectronAPI {
setCookie: (cookieString: string) => Promise<void>; checkUrlAvailable: (url: string) => Promise<{ ok: boolean; status: number; error?: string }>;
checkUrl: (url: string) => Promise<{ ok: boolean; status: number; error?: string }>; setSessionStorage: (key: string, value: string) => void;
getSessionStorage: (key: string) => string | null;
removeSessionStorage: (key: string) => void;
clearSessionStorage: () => void;
} }
declare global { declare global {