I've made a custom titlebar in electron with the icons taken straight from the Windows UI kit.
How can I detect whenever the window is maximized, whether it's by double clicking the titlebar or dragging it to the top of the screen, in another script rather than the main one. I need to change the maximize icon to a "restore" icon when maximized.
I'm aware of this method:
mainWindow.on('maximize', () => {
// do something
})
But I can only modify the HTML in the frontend JS file, not the main one.
If you created a custom titlebar, you must have used IPC for the buttons to update the window. In order to change the HTML from main, you have to also use it here:
Main
mainWindow.on("maximize", () => {
mainWindow.webContents.send("maximize");
});
(You may want to listen to the unmaximize
event too.)
Preload
const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld('electronAPI', {
onMaximize: (callback) => (
ipcRenderer.on("maximize", () => callback())
)
});
Renderer
window.electronAPI.onMaximize(() => {
// Do something with your HTML
});
As a side note, if you want your app to keep the maximized state on lunch, you will need to store the state before close (with a tool such as electron-store
for example), and make your renderer check the state of the window when it's loaded:
Main
const { app, ipcMain } = require("electron");
// Note that starting with version 9,
// `electron-store` is ESM and `require` will not work.
const Store = require("electron-store");
const store = new Store({
schema: {
isMaximized: { type: "boolean" }
}
});
app.whenReady().then(() => {
ipcMain.handle("isMaximized", () => mainWindow.isMaximized());
})
mainWindow.once("ready-to-show", () => {
if (store.get("isMaximized")) mainWindow.maximize();
});
mainWindow.on("close", (event) => {
store.set("isMaximized", mainWindow.isMaximized());
});
Preload
const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld('electronAPI', {
isMaximized: () => ipcRenderer.invoke("isMaximized")
});
Renderer
await window.electronAPI.isMaximized((isMax) => {
// Do something with your HTML
});