I would like to create a menu of favourite or recently opened documents for an Electron application. I can easily track these documents once they have been opened, but how can I dynamically add them to a menu?
What I have learned so far:
Create an menu in the main process:
menu=[ { label: 'Some Application', submenu: [ { label: `Open …`, accelerator: 'CmdOrCtrl+O', id:'OPEN', click: send }, { label: `Documents …`, id:'DOCUMENTS', click: send, submenu: [] }, { type:'separator' }, { role: `quit`, accelerator: 'CmdOrCtrl+Q' } ] }, ];
Use remote
in the render process:
const electron=require('electron'); const { ipcRenderer, shell, remote } = electron; const {app,BrowserWindow,dialog,Menu,MenuItem}=remote;
I have the documents in a JSON file, but I don't know what to do next to add them to the Documents
menu above.
I've been looking into this "recently" ;-).
It is a built in feature: feat: Recent documents menu item #11166
{
label: 'Open Recent',
role: 'recentdocuments',
submenu: [
{
label: 'Clear Recent',
role: 'clearrecentdocuments'
}
]
},
And app.addRecentDocument(path) and app.clearRecentDocuments() can be used. Electron 8 adds this feature: dontAddToRecent to Windows showOpenDialog
I've been able to get it working on macOS
though I haven't been able to figure out how to do the Application Registration thing yet (through electron-builder
, I guess) which is required to get it working on Windows
.
I also saw the code snippet below from here but I haven't had a chance to test it yet. Also, be aware that remote
is going to be deprecated in Electron 9: Deprecate the 'remote' module and move it to userland
function updateRecents(path, clear = false) {
const currentMenu = Menu.getApplicationMenu();
if (!currentMenu) return;
const recents = getItemByKey(currentMenu, 'recents');
if (!recents) return;
// Clear menu if requested.
if (clear) {
config.set('recentDocuments', []);
recents.submenu.clear();
recents.submenu.append(new MenuItem({ key: 'null', label: 'No Recent Documents', enabled: false }));
Menu.setApplicationMenu(currentMenu);
return;
}
const item = new MenuItem({
label: require('path').basename(path),
click: () => this.open(path)
});
// If first recent item clear empty placeholder.
if (recents.submenu.items[0].key == 'null') {
recents.submenu.clear();
recents.submenu.append(item);
}
// Limit to maximum 10 recents.
else if (recents.submenu.items.length >= 10) {
const items = recents.submenu.items;
recents.submenu.clear();
items.push(item);
items.slice(10).forEach((i) => recents.submenu.append(i));
}
// Otherwise just add item.
else recents.submenu.append(item);
// Update application menu.
Menu.setApplicationMenu(currentMenu);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.