1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- // preload.js
- const { contextBridge, ipcRenderer } = require('electron');
- // 暴露安全的API给渲染进程
- contextBridge.exposeInMainWorld('electron', {
- // IPC通信
- ipcRenderer: {
- // 发送消息到主进程(无返回值)
- send: (channel, ...args) => {
- ipcRenderer.send(channel, ...args);
- },
- // 调用主进程方法并获取返回值(Promise)
- invoke: (channel, ...args) => {
- return ipcRenderer.invoke(channel, ...args);
- },
- // 监听来自主进程的消息
- on: (channel, func) => {
- const subscription = (event, ...args) => func(...args);
- ipcRenderer.on(channel, subscription);
- return () => {
- ipcRenderer.removeListener(channel, subscription);
- };
- },
- // 一次性监听来自主进程的消息
- once: (channel, func) => {
- ipcRenderer.once(channel, (event, ...args) => func(...args));
- }
- },
-
- // 操作系统与应用相关信息
- system: {
- // 获取应用版本
- getAppVersion: () => ipcRenderer.invoke('get-app-version')
- },
-
- // 文件操作
- files: {
- // 打开文件选择对话框
- openDirectoryDialog: () => ipcRenderer.invoke('open-directory-dialog'),
- // 在文件管理器中显示文件
- showItemInFolder: (path) => ipcRenderer.invoke('open-file-path', path),
- // 获取文件状态信息
- getFileStats: (path) => ipcRenderer.invoke('get-file-stats', path)
- },
-
- // 外部链接
- shell: {
- // 在默认浏览器中打开URL
- openExternal: (url) => ipcRenderer.invoke('open-url', url)
- }
- });
- window.addEventListener('DOMContentLoaded', () => {
- console.log('Preload script loaded');
- });
-
|