How to import Menu in Electron 15

Viewed 415

I need to import Menu for my render.js file. But either Remote is undefined or I get some error.

With the following code I get this error: Uncaught TypeError: Cannot read properties of undefined (reading 'members')

I also tried something from the Electron Documentation using the .enable(webContents) method, but I cannot get it working either.

What's the way of doing this?

Index.js:

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

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) { // eslint-disable-line global-require
  app.quit();
}

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    }
  });

render.js:

const { desktopCapturer } = require('electron');
const { Menu } = require('@electron/remote')
console.log(Menu);
2 Answers

As read in the npm @electron/remote doc

@electron/remote/main must be initialized in the main process before it can be used from the renderer:

// in the main process:
require('@electron/remote/main').initialize()

I actually fixed this.

First: You need to add these lines in the index.js file:

const remote = require('@electron/remote/main');
remote.initialize()

Then, also in the index.js file, inside the createWindow() function you need to include this:

remote.enable(mainWindow.webContents);

In the render.js file to import menu:

const remote = require('@electron/remote')
const { Menu } = remote;

Check my GitHub repo where I have the files if this didn't work.

The render.js file is: https://github.com/Auax/electron-screen-recorder/blob/main/src/render.js

The index.js file is: https://github.com/Auax/electron-screen-recorder/blob/main/src/index.js

Related