I attempted to create a right click menu item called "Clear Cache" which clears the cache of the program I'm Working on.The problem is that the function that is sending the event with ipcMain is getting ran as soon as the tray item is right clicked, not when the actual Clear Cache button is clicked. The reason for this is because I have my menu set like This:
// clear cache function
const clearCache = () => {
let response = "Successfully cleared cache.";
mainWindow.webContents.send('clearCacheResponse', response);
console.log(response)
};
const menu = [
{ label: '╸Clear all Cache╺', role: clearCache() },
{ label: 'Separator', type: 'separator'},
{ label: '╸Quit Rich Presence╺', role: 'quit' },
];
tray.popUpContextMenu(Menu.buildFromTemplate(menu))
where the role in the label is a function. The issue with this is that it runs when the object is first initialised which means that it is clearing cache whenever you first right click. Is there any other way to run a custom function with Electron's popUpContextMenu, or am I stuck to try and find a workaround. I have done a decent amount of research and have not found a way to only trigger this event on click of the label.Here is the entire code for the right click context menu which I was trying to create:
rightClick = () => {// clear cache function
const clearCache = () => {
let response = "Successfully cleared cache.";
mainWindow.webContents.send('clearCacheResponse', response);
console.log(response)
};
const menu = [
{ label: '╸Clear all Cache╺', role: clearCache() },
{ label: 'Separator', type: 'separator'},
{ label: '╸Quit Rich Presence╺', role: 'quit' },
];
tray.popUpContextMenu(Menu.buildFromTemplate(menu))}
tray.on('right-click', () => {
rightClick()
});
TL:DR; My Function runs when the object is first initialised, trying to find some way to only trigger the function on label click of the context menu item.
Tried: To create a right click context menu where you right click and have the following options:
What I was Expecting: To open the menu and choose the correct option, and for that option to occur correctly.
What Actually Happened: The Clearing Cache function ran as soon as i first initialised the menu object, meaning clears the cache of the user every time they right click.
I was using:
role: clearCache()
.
The correct way to write this for custom functions is:
click: clearCache
(Thanks to vanowm to showing me how to fix this, I did not realise that this was in the documenation until now!)