Issue
I'm using contextBridge
and contextIsolation
to create a custom context menu on click and I'm using this example from the docs: https://github.com/electron/electron/blob/main/docs/api/menu.md#render-process
// renderer
window.addEventListener('contextmenu', (e) => {
e.preventDefault()
ipcRenderer.send('show-context-menu')
})
ipcRenderer.on('context-menu-command', (e, command) => {
// ...
})
// main
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))
})
This works but the context menu appears right under the mouse. I want to supply a custom x and y. In the docs for menu.popup
, I can set an x
and y
property like this:
menu.popup({
window: /* my window object /*,
x: /* x position */,
y: /* y position */,
})
But I don't know how to add these properties to the object that I get back from BrowserWindow.fromWebContents(event.sender)
.
I tried these options:
menu.popup({ ...BrowserWindow.fromWebContents(event.sender), x, y } );
// or
const window = BrowserWindow.fromWebContents(event.sender);
menu.popup({ window, x, y });
and I get this error
Error processing argument at index 1, conversion failure from
at EventEmitter.a.popup (node:electron/js2c/browser_init:81:3188)
It seems like electron doesn't like converting the results from BrowserWindow.fromWebContents(event.sender)
into an object.
I also tried this, but get the same error.
const window = BrowserWindow.fromWebContents(event.sender);
window.x = x;
window.y = y;
menu.popup(window);
Thanks for the help
Solution
The problem ended up being that the x
and y
variables need to be integers and sometimes they were floats. Putting a Math.round
around x
and y
solved the problem. This worked in the end:
const xRound = Math.round(x);
const yRound = Math.round(y);
const window = BrowserWindow.fromWebContents(event.sender);
menu.popup({ window, x: xRound, y: yRound } );
Answered By - mhkeller Answer Checked By - Marilyn (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.