preload.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // 使用 require 避免 ESM 问题
  2. const { contextBridge, ipcRenderer } = require('electron');
  3. // 暴露给渲染进程的 API
  4. contextBridge.exposeInMainWorld('electronAPI', {
  5. // 应用信息
  6. getAppVersion: () => ipcRenderer.invoke('get-app-version'),
  7. getPlatform: () => ipcRenderer.invoke('get-platform'),
  8. // 窗口控制
  9. minimizeWindow: () => ipcRenderer.send('window-minimize'),
  10. maximizeWindow: () => ipcRenderer.send('window-maximize'),
  11. closeWindow: () => ipcRenderer.send('window-close'),
  12. quitApp: () => ipcRenderer.send('app-quit'), // 真正退出应用
  13. isMaximized: () => ipcRenderer.invoke('window-is-maximized'),
  14. onMaximizedChange: (callback: (isMaximized: boolean) => void) => {
  15. ipcRenderer.on('window-maximized', (_event: unknown, isMaximized: boolean) => callback(isMaximized));
  16. },
  17. // 文件操作
  18. selectFile: (options?: { filters?: { name: string; extensions: string[] }[] }) =>
  19. ipcRenderer.invoke('select-file', options),
  20. selectFolder: () => ipcRenderer.invoke('select-folder'),
  21. // 通知
  22. showNotification: (title: string, body: string) =>
  23. ipcRenderer.send('show-notification', { title, body }),
  24. // Webview Cookie 操作
  25. getWebviewCookies: (partition: string, url: string) =>
  26. ipcRenderer.invoke('get-webview-cookies', partition, url),
  27. clearWebviewCookies: (partition: string) =>
  28. ipcRenderer.invoke('clear-webview-cookies', partition),
  29. });
  30. // 类型声明
  31. declare global {
  32. interface Window {
  33. electronAPI: {
  34. getAppVersion: () => Promise<string>;
  35. getPlatform: () => Promise<string>;
  36. minimizeWindow: () => void;
  37. maximizeWindow: () => void;
  38. closeWindow: () => void;
  39. quitApp: () => void;
  40. isMaximized: () => Promise<boolean>;
  41. onMaximizedChange: (callback: (isMaximized: boolean) => void) => void;
  42. selectFile: (options?: { filters?: { name: string; extensions: string[] }[] }) => Promise<string | null>;
  43. selectFolder: () => Promise<string | null>;
  44. showNotification: (title: string, body: string) => void;
  45. getWebviewCookies: (partition: string, url: string) => Promise<Electron.Cookie[]>;
  46. clearWebviewCookies: (partition: string) => Promise<boolean>;
  47. };
  48. }
  49. }