【问题标题】:Electron: Dynamic context menuElectron:动态上下文菜单
【发布时间】:2020-10-25 23:32:23
【问题描述】:

在 Electron 中,有没有办法在上下文菜单中启用/禁用特定的 MenuItem,具体取决于用户右键单击的元素?我还需要有关单击了哪个确切元素的信息并将该信息传递给上下文菜单功能。

例如,假设我的渲染器进程中有这个 html:

<p id="p1">First paragraph</p>
<p id="p2">Second paragraph</p>
<p id="p3">Third paragraph</p>

该窗口的上下文菜单如下所示:

var menu = new Menu();
menu.append(new MenuItem({label: "This menu item is always shown",}));
menu.append(new MenuItem({  // shown only when clicked on p1 or p3
  label: "This menu is not always shown",
  click: function(id){
    // I want variable id to be an id of paragraph that I have clicked on
  }
}));

所以当我右键单击第一段或第三段时,应该会弹出一个包含 2 个项目的上下文菜单。 但是当我右键单击第二段时,应该会弹出一个包含 1 个项目的上下文菜单。 另外,我想将段落 id 作为参数传递给上下文菜单函数,这样我就可以从那里知道我点击了哪个段落。

【问题讨论】:

    标签: javascript node.js electron


    【解决方案1】:

    我会在 contextmenu 事件处理程序中动态(重新)创建上下文菜单:

    在你的主进程中:

    如果加载远程内容,请不要开启 nodeIntegration!

    const { app, BrowserWindow } = require('electron');
    
    function createWindow () {
      let win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          nodeIntegration: true
        }
      });
    
      win.loadFile('index.html');
    }
    
    app.whenReady().then(createWindow);
    

    在您的渲染器进程中:

    注意我是如何“远程”加载 Menu 和 MenuItem 模块的

    <html>
      <head>
        <script>
          const { remote } = require('electron');
          const { Menu, MenuItem } = remote;
    
          window.addEventListener('contextmenu', (e) => {
            e.preventDefault();
            const menu = new Menu();
            menu.append(new MenuItem(new MenuItem({label: "This menu item is always shown"})));
            if (e.target.id === "p1" || e.target.id === "p3") {
              menu.append(new MenuItem({
                label: "This menu is not always shown",
                click: function(){
                  alert(`you clicked on ${e.target.id}`);
                }
              }));
            }
            menu.popup({ window: remote.getCurrentWindow() })
          }, false)
        </script>
      </head>
      <body>
        <p id="p1">First paragraph</p>
        <p id="p2">Second paragraph</p>
        <p id="p3">Third paragraph</p>
      </body>
    </html>  
    

    【讨论】:

    • 在我这边,这会导致“未捕获的类型错误:无法解构 'remote' 的属性 'Menu',因为它未定义。”你知道为什么会这样吗?
    • @maxischl 你可能没有打开webPreferences.nodeIntegration
    • 是的,我有。在我的主进程中,它们设置为 true,但它不起作用:/
    • @maxischl 我想知道这是否可能与 remote 模块的弃用有关。看到这个github.com/electron/electron/issues/21408
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    • 2019-08-16
    • 2017-11-10
    相关资源
    最近更新 更多