1

I want to handle my own undo/redo menu commands and at the same time still support the Electron built-in undo/redo of the webContents object when it is relevant, for example when the user is focused on a text input element.

This answer seems like a good start, but it is incomplete as it does not address the root question, which is how to mix the two things.

Here is how the ideal code would look like when defining the menu item:

    {
        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
            }
        }
    }

The one dollar question is: how do I code the "if focusedWin.webContents thinks it can handle it" test?

1 Answers1

0

I found a solution to my problem. It's not elegant, but it works. The idea is that the built-in Edit menus such as undo/redo/cut/copy/paste/delete/etc. should be managed by the webContents object only when the user is focused on an input or textarea element.

So in my index.html file, I send a message to the Main process when there is a focus or a blur event on input elements. This sets a global variable (yuck!) on the main process side which is used to make the decision between letting webContents do its job or doing it ourselves.

In index.html (I use jQuery and the great messaging system 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 }));

In 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 !");
                    }
                }
            },