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

Electron渲染进程打开原生dialog窗口调用showOpenDialog报错问题问询

错误根因

该报错是因为Electron 14及以上版本已经彻底废弃内置remote模块,且默认开启上下文隔离、禁用Node.js集成,dialog属于主进程专属模块,无法直接在渲染进程中通过require('electron')引入调用,老版本的enableRemoteModule配置也已失效。

正确实现方案(官方推荐IPC通信方式)

1. 编写预加载脚本(preload.js)

上下文隔离开启的状态下,只能通过预加载脚本向渲染进程暴露安全的通信接口:

const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('electronAPI', {
  openFileDialog: () => ipcRenderer.invoke('open-file-dialog')
})

2. 主进程配置(main.js)

主进程中注册IPC监听,调用dialog模块处理文件选择逻辑:

const { app, BrowserWindow, ipcMain, dialog } = require('electron')
const path = require('path')
let mainWindow

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // 关联你编写的preload.js实际路径
      preload: path.join(__dirname, 'preload.js'),
      // 保持默认配置即可,无需关闭上下文隔离或开启Node集成
      contextIsolation: true,
      nodeIntegration: false
    }
  })
  mainWindow.loadFile('index.html')
}

// 注册打开文件选择框的IPC监听
ipcMain.handle('open-file-dialog', async () => {
  const res = await dialog.showOpenDialog({
    properties: ['openFile', 'multiSelections']
  })
  return res.filePaths
})

app.whenReady().then(() => {
  createWindow()
})

3. 渲染进程调用

在前端代码中直接调用预加载暴露的接口即可:

async function getSelectedFiles() {
  const selectedFilePaths = await window.electronAPI.openFileDialog()
  console.log(selectedFilePaths)
}
getSelectedFiles()

替代方案(使用第三方remote模块)

如果要沿用类似老版本remote的调用方式,需要安装官方维护的第三方包@electron/remote:

  1. 安装依赖
    npm install @electron/remote

  2. 主进程初始化remote

const remoteMain = require('@electron/remote/main')
remoteMain.initialize()
// 创建窗口后启用该窗口的remote权限
remoteMain.enable(mainWindow.webContents)
  1. 预加载脚本暴露dialog接口
const { contextBridge } = require('electron')
const dialog = require('@electron/remote').dialog
contextBridge.exposeInMainWorld('electronAPI', {
  showOpenDialog: (opts) => dialog.showOpenDialog(opts)
})
  1. 渲染进程调用
window.electronAPI.showOpenDialog({ properties: ['openFile', 'multiSelections'] })
  .then(res => console.log(res.filePaths))

内容的提问来源于stack exchange,提问作者Tamás Polgár

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:45:04