解决Electron客户端主进程中设置nodeIntegration为true,渲染进程中依旧无法使用remote模块的问题

使用Electron开发的客户端产品很多,比如耳熟能详的VSCode、WhatsApp、Microsoft Teams......此外,AnyShare的新客户端也是采用Electron技术所开发。如果要开发跨平台的客户端,Electron一定是首选。

很长一段时间内你使用Electron开发客户端时使用的版本很可能是以前的老版本,在你将低版本的Electron升级至高版本时你一定会发现主进程中设置nodeIntegration为true后,渲染进程中依旧无法使用remote模块,如何解决?

较低版本的electron(v10以前的版本)

在主进程中设置nodeIntegration: true后,只需要从electron中引入remote即可

const remote = require('electron');

较高版本的electron(以19.0.8为例)

1、先安装模块@electron/remote

npm install --save @electron/remote

2、主进程中设置nodeIntegration:true,contextIsolation: false(如果是V10,则只要设置nodeIntegration为true即可),同时在创建窗口实例之后引入模块

require('@electron/remote/main').initialize()
require("@electron/remote/main").enable(win.webContents)

main.js

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

function createWindow() {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        show: false,
        // frame: true,
        // autoHideMenuBar: true,
        title: "Samve",
        // icon: "",
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            //enableRemoteModule: true
        }
    })

    require('@electron/remote/main').initialize()
    require("@electron/remote/main").enable(win.webContents)

    win.loadFile('index.html')

    win.on("ready-to-show", function(){
        win.show();
    })
}

app.on("ready", function(){
    createWindow();
})

3.在渲染进程中导入remote模块

const remote = require("@electron/remote")

完成后即可在渲染进程中使用remote模块,例如:

const remote = require("@electron/remote");
const { ipcRenderer } = require("electron");

console.log("remote");
console.log(remote);

ipcRenderer.on("mainSendToRender", function (event, arg) {
  console.log("This message comes from main process.");
  console.log("event:", event);
  console.log("arg:", arg);
});

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值