【问题标题】:electron.remote is undefined in render processelectron.remote 在渲染过程中未定义
【发布时间】:2025-11-24 19:00:02
【问题描述】:

当用户单击按钮时,我尝试使用对话框,错误出现错误Uncaught TypeError: Cannot read property 'dialog' of undefined。控制台日志的结果是undefined

main.js文件

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

if (require('electron-squirrel-startup')) {
  app.quit();
}

const createWindow = () => {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  });
  mainWindow.loadFile(path.join(__dirname, './src/index.html'));

  mainWindow.webContents.openDevTools();
};

app.on('ready', createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

index.html文件

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>welcome</title>
    <link rel="stylesheet" href="index.css">
  </head>
  <body>
    <p id="create">Create New File</p>
    <p id="open">Open File</p>
    <script src="./index.js"></script>
  </body>
</html>

index.js文件

const { remote } = require('electron');
console.log(remote); // undefined

const open = document.querySelector('#open');
const create = document.querySelector('#create');

open.addEventListener('click', function () {
  remote.dialog.showErrorBox('error', '123'); 
});

【问题讨论】:

    标签: javascript electron


    【解决方案1】:
    webPreferences: {
          nodeIntegration: true,
          enableRemoteModule: true
        }
    

    添加enableRemoteModule。我认为您使用的是最新版本的 Electron,默认情况下我们不能在渲染器上使用 remote 模块。需要添加这个标志来启用它。

    参考:https://github.com/electron/electron/issues/21408

    【讨论】:

    最近更新 更多