Electron IPC Main webContents 不向渲染器发送数据

问题描述 投票:0回答:1

使用 Electron 网站上的文档,我无法使用

mainWindow.webContents.send('send-data-channel', data)
发送简单数据。

我正在尝试使用 Node 的

fs
模块将 JSON 文件发送到渲染器。

main.js

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();
...
});

预加载.js

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
})

渲染器.js

hotkeys('f11', function(e) {
  e.preventDefault();
  electronAPI.fullScreen();
}) // Works fine

electronAPI.loadDefaultJSON( (value) => {
  console.log(value)
}); // Nothing coming through
javascript json electron ipc renderer
1个回答
0
投票

需要在窗口加载后触发发送数据。

(感谢@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 ***")
    }
  })
})
© www.soinside.com 2019 - 2024. All rights reserved.