在渲染过程中没有定义electron.remote

bea*_*ang 1 javascript electron

我试图在用户单击按钮时使用对话框,错误出现错误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();
  }
});
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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'); 
});
Run Code Online (Sandbox Code Playgroud)

小智 5

webPreferences: {
      nodeIntegration: true,
      enableRemoteModule: true
    }
Run Code Online (Sandbox Code Playgroud)

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

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