'how to apply electron-context-menu in window?

I installed electron-context-menu using the command

npm i electron-context-menu

And then I used the code that is on this site

const {app, BrowserWindow} = require('electron');
const contextMenu = require('electron-context-menu');
    
contextMenu({
    showSaveImageAs: true
});
    
let mainWindow;

(async () => {
    await app.whenReady();
    
    mainWindow = new BrowserWindow({
        webPreferences: {
            spellcheck: true
        }
    });
})();

But when I right click on the window, the ContextMenu with the items doesn't appear.

A white window only appears:

enter image description here

What should I do to make ContextMeu appear?



Solution 1:[1]

You won't need a lib for do this (And IMO you Shouldn't). The electron API already give to you a context-menu ready to use. If you already use contextBridge just follow the electron site steps.

main.ts

// ...
ipcMain.on('show-context-menu', (event) => {
  const template = [
    {
      label: 'Menu Item 1',
      click: () => { event.sender.send('context-menu-command', 'menu-item-1') }
    },
    { type: 'separator' },
    { label: 'Menu Item 2', type: 'checkbox', checked: true }
  ]
  const menu = Menu.buildFromTemplate(template)
  menu.popup(BrowserWindow.fromWebContents(event.sender))
})

renderer.ts

window.addEventListener('contextmenu', (e) => {
  e.preventDefault()
  ipcRenderer.send('show-context-menu')
})

ipcRenderer.on('context-menu-command', (e, command) => {
  // What it will do when this options is click it
})

You can create a preload for each action too if you want Also, if you want the browser default contextMenu, here comes a example.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brenno Araujo