preload.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // preload.js
  2. const { contextBridge, ipcRenderer } = require('electron');
  3. // 暴露安全的API给渲染进程
  4. contextBridge.exposeInMainWorld('electron', {
  5. // IPC通信
  6. ipcRenderer: {
  7. // 发送消息到主进程(无返回值)
  8. send: (channel, ...args) => {
  9. ipcRenderer.send(channel, ...args);
  10. },
  11. // 调用主进程方法并获取返回值(Promise)
  12. invoke: (channel, ...args) => {
  13. return ipcRenderer.invoke(channel, ...args);
  14. },
  15. // 监听来自主进程的消息
  16. on: (channel, func) => {
  17. const subscription = (event, ...args) => func(...args);
  18. ipcRenderer.on(channel, subscription);
  19. return () => {
  20. ipcRenderer.removeListener(channel, subscription);
  21. };
  22. },
  23. // 一次性监听来自主进程的消息
  24. once: (channel, func) => {
  25. ipcRenderer.once(channel, (event, ...args) => func(...args));
  26. }
  27. },
  28. // 操作系统与应用相关信息
  29. system: {
  30. // 获取应用版本
  31. getAppVersion: () => ipcRenderer.invoke('get-app-version')
  32. },
  33. // 文件操作
  34. files: {
  35. // 打开文件选择对话框
  36. openDirectoryDialog: () => ipcRenderer.invoke('open-directory-dialog'),
  37. // 在文件管理器中显示文件
  38. showItemInFolder: (path) => ipcRenderer.invoke('open-file-path', path),
  39. // 获取文件状态信息
  40. getFileStats: (path) => ipcRenderer.invoke('get-file-stats', path)
  41. },
  42. // 外部链接
  43. shell: {
  44. // 在默认浏览器中打开URL
  45. openExternal: (url) => ipcRenderer.invoke('open-url', url)
  46. }
  47. });
  48. window.addEventListener('DOMContentLoaded', () => {
  49. console.log('Preload script loaded');
  50. });