【问题标题】:How to mix your own undo and webContents.undo() in Electron?如何在 Electron 中混合使用自己的 undo 和 webContents.undo()?
【发布时间】:2021-11-26 16:21:10
【问题描述】:

我想处理我自己的撤消/重做菜单命令,同时在相关时仍支持电子内置的 webContents 对象的撤消/重做,例如当用户专注于文本输入元素时.

This answer 似乎是一个好的开始,但它并不完整,因为它没有解决根本问题,即如何将两者混合。

这是定义菜单项时理想代码的样子:

    {
        label:       'Undo',
        accelerator: 'CmdOrCtrl+Z',
        click:       function(menuItem, focusedWin) {
            if (*** focusedWin.webContents thinks it can handle it ***) {
                focusedWin.webContents.undo();
            } else {
                // Run my own code
            }
        }
    }

一美元的问题是:我如何编写“iffocusedWin.webContents 认为它​​可以处理它”测试?

【问题讨论】:

    标签: menu electron


    【解决方案1】:

    我找到了解决问题的方法。它并不优雅,但它确实有效。这个想法是内置的编辑菜单,如撤消/重做/剪切/复制/粘贴/删除/等。只有当用户专注于输入或文本区域元素时,才应由 webContents 对象管理。

    所以在我的 index.html 文件中,当输入元素上有焦点或模糊事件时,我会向主进程发送一条消息。这会在主进程端设置一个全局变量(糟糕!),用于在让 webContents 完成工作或自己完成工作之间做出决定。

    在 index.html 中(我使用 jQuery 和出色的消息传递系统 described in this other thread):

    //-- Tell the main process if the preset Edit menus should be activated or not.
    //   Typically we active it only when the active item has text input
    $('input').focus(() => window.api.send("menus:edit-buildin", { turnItOn: true }));
    $('input').blur(() => window.api.send("menus:edit-buildin", { turnItOn: false }));
    

    在 main.js 中:

    // This is a global :-( to track if we should enable and use
    // the preset Edit menus: undo/redo/cut/copy/paste/delete
    var menusEditPreset = false;
    
    // Listen to the renderer
    ipcMain.on("menus:edit-buildin", (event, { turnItOn }) => {
        menusEditPreset = turnItOn;
    });
    
    // ... and in the menu definition:
    
                {
                    id: 'undo',
                    label: 'Undo',
                    accelerator: 'CmdOrCtrl+Z',
                    click: (event, focusedWindow, focusedWebContents) => {
                        if (menusEditPreset) {
                            focusedWindow.webContents.undo();
                        } else {
                            console.log("My own undo !");
                        }
                    }
                },
    
    

    【讨论】:

      猜你喜欢
      • 2016-09-09
      • 1970-01-01
      • 2017-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-17
      • 2019-08-07
      • 2021-03-31
      相关资源
      最近更新 更多