我使用contextBridge和contextIsolation在单击时创建自定义上下文菜单,并在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))
})这是可行的,但是上下文菜单就出现在鼠标下面。我想提供一个自定义的x和y. In the docs for menu.popup,我可以设置如下的x和y属性:
menu.popup({
window: /* my window object /*,
x: /* x position */,
y: /* y position */,
})但我不知道如何将这些属性添加到从BrowserWindow.fromWebContents(event.sender)返回的对象中。
我尝试了这些选择:
menu.popup({ ...BrowserWindow.fromWebContents(event.sender), x, y } );
// or
const window = BrowserWindow.fromWebContents(event.sender);
menu.popup({ window, x, y });我得到了这个错误
Error processing argument at index 1, conversion failure from
at EventEmitter.a.popup (node:electron/js2c/browser_init:81:3188)似乎电子不喜欢将来自BrowserWindow.fromWebContents(event.sender)的结果转换为一个对象。
我也尝试过这个,但是得到了同样的错误。
const window = BrowserWindow.fromWebContents(event.sender);
window.x = x;
window.y = y;
menu.popup(window);谢谢你的帮助
发布于 2022-03-07 22:01:04
问题的结果是,x和y变量需要是整数,有时它们是浮点数。把Math.round放在x和y上解决了这个问题。这最终起了作用:
const xRound = Math.round(x);
const yRound = Math.round(y);
const window = BrowserWindow.fromWebContents(event.sender);
menu.popup({ window, x: xRound, y: yRound } );https://stackoverflow.com/questions/71376903
复制相似问题