在我的 React/Electronjs 项目中,这是我想要实现的目标:
我面临的问题:
// main.js
const { app, BrowserWindow, dialog, Menu, ipcMain } = require('electron')
const fs = require('fs')
const os = require('node:os')
const path = require('node:path')
require('@electron/remote/main').initialize()
const isMac = process.platform === 'darwin'
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
titleBarStyle: "default",
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
preload: path.join(__dirname, 'preload.js')
}
})
win.setRepresentedFilename(os.homedir())
win.setDocumentEdited(true)
win.loadURL('http://localhost:3000')
const template = [
...(isMac
? [{
label: app.name,
submenu: [
{ role: 'about' },
{ type: 'separator' },
{ role: 'services' },
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideOthers' },
{ role: 'unhide' },
{ type: 'separator' },
{ role: 'quit' }
]
}]
: []),
// { role: 'fileMenu' }
{
label: 'File',
submenu: [
{
label: 'Open File',
click: () => {
const files = dialog.showOpenDialogSync(win,
{
properties: ['openFile'],
filters: [{ name: "Text Files", extensions: ['txt'] }]
}
);
// If no files
if (!files) return;
const file = files[0];
//const fileContent = fs.promises.readFile(file, 'utf-8');
const fileContent = fs.readFileSync(file).toString();
win.webContents.send('open-file', fileContent)
}
}
]
}
]
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
return win
}
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
// preload.js
const { contextBridge, ipcRenderer } = require('electron/renderer');
contextBridge.exposeInMainWorld('electronAPI', {
openFile: (callback) => ipcRenderer.on('open-file', (_event, content) => callback(content))
})
//预加载.js
const { contextBridge, ipcRenderer } = require('电子/渲染器');
contextBridge.exposeInMainWorld('电子API', { openFile: (回调) => ipcRenderer.on('打开文件', (_event, content) => 回调(内容)) })