You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过preload.js实现Electron向React发送数据?

解决Electron向React发送数据的问题

1. 修正Preload脚本(preload.js)

必须通过contextBridge安全封装IPC监听方法,严格遵循Electron上下文隔离规范,不能直接暴露ipcRenderer对象:

const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
  // 封装监听showAnimation事件的方法
  onShowAnimation: (callback) => {
    ipcRenderer.on('showAnimation', (_, args) => callback(args));
  },
  // 封装移除监听的方法,防止内存泄漏
  removeShowAnimationListener: () => {
    ipcRenderer.removeAllListeners('showAnimation');
  }
});

2. 确认Electron主进程配置(electron.js)

确保窗口创建时正确指定preload路径,且上下文隔离处于开启状态:

const { app, BrowserWindow } = require('electron');
const path = require('path');

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // 必须使用绝对路径指定preload脚本
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true, // 强制开启,安全要求
      nodeIntegration: false // 必须关闭,禁止渲染进程直接访问Node.js
    }
  });

  win.loadURL('http://localhost:3000'); // React开发环境地址,打包后替换为loadFile

  // 测试发送消息(确保窗口加载完成后发送)
  win.webContents.on('did-finish-load', () => {
    win.webContents.send('showAnimation', { type: 'fade', duration: 1000 });
  });
}

app.whenReady().then(createWindow);

3. React端接收消息的正确写法

在组件挂载时注册监听,卸载时移除监听,同时兼容浏览器开发环境:

import { useEffect } from 'react';

function AnimationComponent() {
  useEffect(() => {
    // 避免浏览器环境下报错
    if (!window.electronAPI) return;

    const handleAnimation = (args) => {
      console.log('收到Electron消息:', args);
      // 执行对应动画逻辑
      if (args.type === 'fade') {
        document.body.style.transition = `opacity ${args.duration}ms`;
        document.body.style.opacity = '0';
        setTimeout(() => document.body.style.opacity = '1', 100);
      }
    };

    // 注册监听
    window.electronAPI.onShowAnimation(handleAnimation);

    // 组件卸载时清理监听
    return () => {
      window.electronAPI.removeShowAnimationListener();
    };
  }, []);

  return <div>动画展示区域</div>;
}

export default AnimationComponent;

4. 常见问题排查

  • 确保preload脚本未被打包工具篡改,若使用electron-builder,需在package.json中配置extraResources保证preload路径正确。
  • 检查IPC事件名称大小写完全一致,主进程发送与渲染进程监听的字符串必须完全匹配。
  • 确认消息发送时机在窗口加载完成后(如did-finish-load回调内),避免窗口未就绪导致消息丢失。

内容的提问来源于stack exchange,提问作者Hack Try

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 16:40:32