使用 Electron 网站上的文档,我无法使用
mainWindow.webContents.send('send-data-channel', data)
发送简单数据。
我正在尝试使用 Node 的
fs
模块将 JSON 文件发送到渲染器。
import { app, BrowserWindow, ipcMain, ipcRenderer, dialog } from 'electron'
import path from 'node:path';
const fs = require('fs');
// More stuff here...
const createWindow = () => {
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
contextIsolation: true,
},
darkTheme: true,
icon: 'src/img/logo.png'
});
// Set Fullscreen (to demonstrate a process that works fine)
ipcMain.on('set-fullscreen', () => {
if (mainWindow.isFullScreen() == true) {
mainWindow.setFullScreen(false);
} else {
mainWindow.setFullScreen(true);
}
});
// *** Here is where I'm attempting to load a default file at startup. ***
fs.readFile('src/project-files/default.json', 'utf-8', (err, jsonData) => {
if (err) {
console.log(err);
return;
} else {
console.log("*** Successfully read JSON file"); // Terminal shows this
mainWindow.webContents.send('load-default-json-file', jsonData); // No warning from terminal here
console.log("*** Sent JSON data ***") // Terminal shows this
}
});
...
};
app.whenReady().then(() => {
createWindow();
...
});
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('electronAPI', {
loadDefaultJSON: (callback) => ipcRenderer.on('load-default-json-file', (_event, value) => callback(value)),
fullScreen: () => ipcRenderer.send('set-fullscreen') // This works
})
hotkeys('f11', function(e) {
e.preventDefault();
electronAPI.fullScreen();
}) // Works fine
electronAPI.loadDefaultJSON( (value) => {
console.log(value)
}); // Nothing coming through
需要在窗口加载后触发发送数据。
(感谢@Arkellys 和@Timur。)
mainWindow.webContents.on('did-finish-load', () => {
fs.readFile('src/project-files/default.json', 'utf-8', (err, data) => {
if (err) {
console.log(err);
return;
} else {
console.log("*** Successfully read JSON file");
mainWindow.webContents.send('load-default-json-file', data);
console.log("*** Sent JSON data ***")
}
})
})