【Electron】electron+react的插件@electron/remote用法,在渲染进程直接调用主进程的API

发布于:2025-06-27 ⋅ 阅读:(13) ⋅ 点赞:(0)


electron的remote是一个electron模块,它将JavaScript对象从主进程桥接到渲染进程,是在electron 14.0.0版本之前使用!!!在electron 14.0.0以后,remote这个模块已经被废弃;后续的版本官方建议直接去使用主进程和渲染进程之间的IPC通信来实现 【感兴趣的可以点击这一篇查看IPC通信的使用】

1、首先安装使用

yarn add --save @electron/remote 
或者是
npm install --save @electron/remote

在这里插入图片描述
我这个是在一个空的文件夹下安装的,方便从外网迁移到内网的项目中,可以把remote相关的直接迁移到你的内网进行使用【因为我内网没办法进行直接安装】;

2、再进行初始化

@electron/remote/main必须在主进程中初始化,然后才可以在渲染进程中直接使用

// 也就是我们在主进程那种进行初始化
require('@electron/remote/main').initialize()

如图所示,这是我在主进程中添加的:
这里要把contextIsolation:改为false,允许在渲染进程使用Node【但是有安全风险】
在这里插入图片描述

3、在渲染进程中使用

const { BrowserWindow } = window.require(‘@electron/remote’);
或者引入其他的
以下是我在开发过程中的使用方式,我要使用electron的shell 去 实现一个打开文件;

import React from 'react';
const { app, shell } = window.require('@electron/remote');
const path = window.require('path');
const fs = window.require('fs');


const UserManualButton = () => {
  const handleUserManual = () => {
    // 获取系统下载目录并拼接路径
    const downloadsPath = app.getPath('downloads');
    const manualPath = path.join(downloadsPath, 'New', 'testFile.pdf');

    // 检查文件是否存在
    if (fs.existsSync(manualPath)) {
      shell.openPath(manualPath)
        .then(() => console.log('文件打开成功'))
        .catch(err => console.error('打开失败:', err));
    } else {
      console.error('文件不存在:', manualPath);
    }
  };

  return (
    <button onClick={handleUserManual}>打开用户手册</button>
  );
};

export default UserManualButton;

但是在这里会有安全风险:contextIsolation: false 会降低应用安全性,因为渲染进程可以直接访问 Node.js API
后续在大于electron 14版本就用到刚刚上方提到的IPC通信,并且为什么@electron/remote被废弃

electron官网

以上就是一个简单的使用了


网站公告

今日签到

点亮在社区的每一天
去签到