preload.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // preload.js
  2. const { contextBridge, ipcRenderer } = require('electron');
  3. // 暴露安全的 API 给渲染进程
  4. contextBridge.exposeInMainWorld('electronAPI', {
  5. // 系统退出相关操作
  6. exitApp: () => ipcRenderer.invoke('exit-close'),
  7. shutdownSystem: () => ipcRenderer.invoke('exit-shutdown'),
  8. // 日志功能(保留原有功能)
  9. writeLog: (level, msg) => ipcRenderer.invoke('write-log', level, msg),
  10. // 文件保存功能
  11. /**
  12. * 保存 Blob 数据到文件
  13. * @param {Object} options - 保存选项
  14. * @param {ArrayBuffer} options.data - 文件数据(ArrayBuffer)
  15. * @param {string} options.defaultFilename - 默认文件名
  16. * @param {Array} options.filters - 文件类型过滤器
  17. * @param {string} options.title - 对话框标题
  18. * @returns {Promise<{success: boolean, filePath?: string, canceled?: boolean, error?: string}>}
  19. */
  20. saveFile: (options) => ipcRenderer.invoke('save-blob', options)
  21. });
  22. // 暴露存储API
  23. contextBridge.exposeInMainWorld('electronStorage', {
  24. /**
  25. * 获取存储项
  26. * @param {string} key - 存储键
  27. * @returns {Promise<string|null>} 存储的值
  28. */
  29. getItem: (key) => ipcRenderer.invoke('storage-get', key),
  30. /**
  31. * 设置存储项
  32. * @param {string} key - 存储键
  33. * @param {string} value - 要存储的值
  34. * @returns {Promise<void>}
  35. */
  36. setItem: (key, value) => ipcRenderer.invoke('storage-set', key, value),
  37. /**
  38. * 删除存储项
  39. * @param {string} key - 存储键
  40. * @returns {Promise<void>}
  41. */
  42. removeItem: (key) => ipcRenderer.invoke('storage-remove', key),
  43. });
  44. // 暴露打印API
  45. contextBridge.exposeInMainWorld('electronPrint', {
  46. /**
  47. * 打印HTML内容(传统方式)
  48. * @param {Object} options - 打印选项
  49. * @param {string} options.html - 要打印的HTML内容
  50. * @param {string} options.orientation - 打印方向 ('portrait' | 'landscape')
  51. * @param {string} options.paperSize - 纸张尺寸 ('A3' | 'A4')
  52. * @param {boolean} options.silent - 是否静默打印
  53. * @param {Object} options.margins - 页边距
  54. */
  55. print: (options) => ipcRenderer.invoke('print-film', options),
  56. /**
  57. * 打印HTML内容(使用File System API)
  58. * @param {Object} options - 打印选项
  59. * @param {string} options.html - 要打印的HTML内容
  60. * @param {Array} options.imageDataList - 图片数据数组
  61. * @param {string} options.orientation - 打印方向 ('portrait' | 'landscape')
  62. * @param {string} options.paperSize - 纸张尺寸 ('A3' | 'A4')
  63. * @param {boolean} options.silent - 是否静默打印
  64. * @param {Object} options.margins - 页边距
  65. */
  66. printToFile: (options) => ipcRenderer.invoke('print-film-to-file', options),
  67. /**
  68. * 导出为PDF
  69. * @param {Object} options - 导出选项
  70. */
  71. printToPDF: (options) => ipcRenderer.invoke('print-to-pdf', options),
  72. });