Skip to content

Save / restore window state #526

Closed as not planned
Closed as not planned

Description

@quasado

Is there any API to save/restore the window's size / state / position? If not, what's the advised approach to do so?

Activity

  1. zcbenz commented on Jul 29, 2014

    @zcbenz
    Contributor

    There is not such API and no plan for it. You can store window's state in either a file or via localStorage.

  2. imskull commented on Aug 20, 2015

    @imskull

    For anyone needs.
    In your init js:

    app.on('ready', function() {
      var path = require("path");
      var fs = require("fs");
      var initPath = path.join(app.getDataPath(), "init.json");
      var data;
      try {
        data = JSON.parse(fs.readFileSync(initPath, 'utf8'));
      }
      catch(e) {
      }
      // Create the browser window.
      mainWindow = new BrowserWindow((data && data.bounds) ? data.bounds : {width: 800, height: 600});
      ...
      mainWindow.on("close", function() {
        var data = {
          bounds: mainWindow.getBounds()
        };
        fs.writeFileSync(initPath, JSON.stringify(data));
      }
      ...
    }
    

    I couldn't find any way to use localStorage in the init js, have to use "fs" module instead.

  3. zeke commented on Sep 9, 2016

    @zeke
    Contributor

    Thanks for the snippet, @imskull. I used electron-config to persist the bounds to disk. Here's what I ended up with:

    const {app, BrowserWindow} = require('electron')
    const Config = require('electron-config')
    const config = new Config()
    let win
    
    app.on('ready', () => {
      let opts = {show: false}
      Object.assign(opts, config.get('winBounds'))
      win = new BrowserWindow(opts)
      win.loadURL(`file://${__dirname}/app/index.html`)
    
      win.once('ready-to-show', win.show)
    
      // save window size and position
      win.on('close', () => {
        config.set('winBounds', win.getBounds())
      })
    })
  4. steverandy commented on Sep 9, 2016

    @steverandy

    @zeke Is it safe to do fs operation during close event?
    If user quits the app, how do we make sure file has been written?

  5. MarshallOfSound commented on Sep 9, 2016

    @MarshallOfSound
    Member

    @steverandy Doing synchronous fs operations in the close event will work. Asynchronous operations are not guaranteed to be completed.

  6. zeke commented on Sep 9, 2016

    @zeke
    Contributor

    safe to do fs operation during close event?

    Speaking of saving data when the app is closed: I used electron-config instead of localStorage because localStorage only saves if the app exits "cleanly". So if you kill your process (say with ^C) you're out of luck.

    See #1731 (comment)

  7. andymartinwork commented on Sep 15, 2016

    @andymartinwork

    Just for future visitors to this bug

    The code above does not take into account if the app is

    • saved on an external monitor
    • quit
    • external monitor disconnected
    • app opened again

    You can quite often end up with the app being off the end of the screen (dependent on zoom factor). So something more complicated is necessary for a professional implementation.

  8. whyboris commented on Dec 26, 2018

    @whyboris
  9. zeke commented on Dec 26, 2018

    @zeke
    Contributor

    The electron-window-state module is also a good option for this.

  10. whyboris commented on Dec 26, 2018

    @whyboris

    Probably worth keeping in mind if you hand-code your own implementation: you'll likely need to handle resolution changes (change of monitor or otherwise). The last position & dimensions might result in your app appearing off-screen with no way to get it back (e.g. you're on a 4K screen, app is on the right half; you go down to 1080p screen and your app is no longer accessible).

  11. sertxudev commented on Jun 1, 2019

    @sertxudev

    Just for future visitors to this bug

    The code above does not take into account if the app is

    • saved on an external monitor
    • quit
    • external monitor disconnected
    • app opened again

    You can quite often end up with the app being off the end of the screen (dependent on zoom factor). So something more complicated is necessary for a professional implementation.

    I solved this problem with this code:

    let window = {x: 267, y: 195} // Saved previous window position
    let screen = electron.screen.getDisplayNearestPoint({ x: window.x, y: window.y })
    if (!(window.x > screen.bounds.x && window.x < screen.size.width) || !(window.y > screen.bounds.y && window.y < screen.size.height)) {
        // The requested position cannot be accesible so the nearest point is applied
        window.x = screen.bounds.x
        window.y = screen.bounds.y
    }
  12. simonbuchan commented on Dec 8, 2019

    @simonbuchan

    The above code has a couple of bugs, e.g. comparing window.x to just .width, instead of .x + .width, using screen.bounds instead of .workArea, and not considering window size, and it will place the window at the top-left corner, which is a little ugly.

    I've had success with this code to restore the position:

    const options = {
      title: "My Saved Window",
      ...
    };
    
    const bounds = getSavedBounds();
    if (bounds) {
      const area = electron.screen.getDisplayMatching(bounds).workArea;
      // If the saved position still valid (the window is entirely inside the display area), use it.
      if (
        bounds.x >= area.x &&
        bounds.y >= area.y &&
        bounds.x + bounds.width <= area.x + area.width &&
        bounds.y + bounds.height <= area.y + area.height
      ) {
        options.x = bounds.x;
        options.y = bounds.y;
      }
      // If the saved size is still valid, use it.
      if (bounds.width <= area.width || bounds.height <= area.height) {
        options.width = bounds.width;
        options.height = bounds.height;
      }
    }
    
    const window = new BrowserWindow(options);
    

    There are other options, but this one is pretty safe and clear.

    To save, I debounce the move and resize events:

    window.on("resize", saveBoundsSoon);
    window.on("move", saveBoundsSoon);
    let saveBoundsCookie;
    
    function saveBoundsSoon() {
      if (saveBoundsCookie) clearTimeout(saveBoundsCookie);
      saveBoundsCookie = setTimeout(() => {
        saveBoundsCookie = undefined;
        state.bounds = window.getNormalBounds();
        fs.writeFileSync(statePath, JSON.stringify(state, null, 2));
      }, 1000);
    }
    

    Note the use of window.getNormalBounds(), so you're not saving the maximized bounds.

  13. jayenashar commented on Jan 30, 2020

    @jayenashar

    How does Developer Tools remember its dock location and size?

  14. zcbenz commented on Aug 25, 2021

    @zcbenz
    Contributor

    I'm reopening this issue since this has proven to be an actually quite popular request and lots of apps have been implementing their own solutions.

  15. reopened this on Aug 25, 2021
  16. Tetrax-10 commented on Dec 16, 2022

    @Tetrax-10

    Above codes are buggy and complex, so i implemented this after a lot of testing this is the most accurate and simple solution to remember window properties.

    I used electron-store to store values, you can use any storage lib you like.

    Actual Implementation for your reference - My Project's Main.js

    main.js

    import Store from "electron-store"
    let CONFIG = new Store()
    
    let windowConfig = {
        width: 1280,
        height: 680,
    }
    
    function createWindow() {
        Object.assign(windowConfig, CONFIG.get("winBounds"))
        mainWindow = new BrowserWindow(windowConfig)
        if (windowConfig.isMaximized) {
            mainWindow.maximize()
        }
        mainWindow.on("close", () => {
            Object.assign(windowConfig, {
                isMaximized: mainWindow.isMaximized()
            }, mainWindow.getNormalBounds())
            CONFIG.set("winBounds", windowConfig) // saves window's properties using electron-store
        })
    }
  17. jerothor commented on Jan 9, 2023

    @jerothor

    thanks to @Tetrax-10 , using that nifty electron-store lib:

    const { app, BrowserWindow } = require('electron')
    const path = require('path')
    const Store = require('electron-store')
    const store = new Store()
    
    function createWindow() {
        const win = new BrowserWindow({
            webPreferences: {
                preload: path.join(__dirname, 'preload.js'),
            }
        })
    
        win.setBounds(store.get('bounds'))
    
        win.on('close', () => {
            store.set('bounds', win.getBounds())
        })
    
        win.loadFile('index.html')
    }

    it even works for multiple monitors!

  18. nicholaszuccarelli commented on Jan 17, 2023

    @nicholaszuccarelli

    @jerothor Perfect solution. Works a treat!

  19. sascha-schieferdecker commented on Aug 3, 2023

    @sascha-schieferdecker

    thanks to @Tetrax-10 , using that nifty electron-store lib:

    const { app, BrowserWindow } = require('electron')
    const path = require('path')
    const Store = require('electron-store')
    const store = new Store()
    
    function createWindow() {
        const win = new BrowserWindow({
            webPreferences: {
                preload: path.join(__dirname, 'preload.js'),
            }
        })
    
        win.setBounds(store.get('bounds'))
    
        win.on('close', () => {
            store.set('bounds', win.getBounds())
        })
    
        win.loadFile('index.html')
    }

    it even works for multiple monitors!

    Please note: This code does not consider if monitors are removed or changed. If you need to account for more complex setups, you need to compare if the saved bounds fit the screen closest matching the saved bounds. Something like this could help:

            const savedBounds = appStore.get('bounds')
            if (savedBounds !== undefined) {
                const screenArea = screen.getDisplayMatching(savedBounds).workArea
                if (
                    (savedBounds.x > screenArea.x + screenArea.width || savedBounds.x < screenArea.x) ||
                    (savedBounds.y < screenArea.y || savedBounds.y > screenArea.y + screenArea.height)
                ) {
                    // Reset window into existing screenarea
                    win.setBounds({ x: 0, y: 0, width: 1024, height: 768})
                }
                else {
                    win.setBounds(appStore.get('bounds'))
                }
            }
  20. adham667 commented on Feb 21, 2024

    @adham667

    it says on your Google Summer of Code 2024 Ideas List that C++ is required to solve this issue isn't typescript sufficient to solve the problem ?

  21. kkocdko commented on Sep 17, 2024

    @kkocdko

    I wrote a post to summarize some cautions of window state restore. If someone want to implement it, please consider reading this to check the corner cases. In many platform.

    https://kkocdko.site/post/202409161747

    Full content here (click to unfold)

    This note is a conclusion description of the group chat yesterday. Includes Chuyu-Team members and me and more anonymous people. Thanks!

    Restore?

    If your app is like Game Launcher or Login Dialog, has fixed size, then it's recommended to be placed in the center. Or it's usually better to store/restore the window state.

    Restore what?

    Referring to popular apps and os, we recommend always restore the size (width,height) as the best practice. You'd better remember to restore the "maximized" state.

    To go further, you can also store the scale factor and reset the size if you notice a scale/resolution change. Of course you can also do sophisticated calculations to make the app keep a reasonable size even after the scale change, but I don't think this is reliable or standard practice.

    However there are many details to consider when restore the window position (x,y).

    For all platforms, does the position of the new window opening cover the smaller windows of other apps? In desktop such as windows, system will automatically set a "reasonable" position if it's not specified, usually a little to the right down of the currently focused window, so new window appears nicely and allows the previous window to still be adjustable by dragging the title bar.

    For Windows, should we exclude Snap Windows (left-right/quad split screen) from the position store? Explorer excluded, Chromium, QQ and others does not. If you don't exclude it, your window will looks like splitted (similar size and position) but the system doesn't think so (the Snap Windows features doesn't work), it's fucking weird. In Win11, splitted windows use square corners instead of rounded one. And the fast adjustment of neighbors, as well as the auto window fill, will not work.

    On windows, some apps will use the new WinAPI to support Snap Windows (some of which are still undocumented), but have you noticed, this is the trap! Back in the days of Win7, Snap Windows only supported left/right split, which caused some apps to store and restore to the basic left/right split after being switched to quad split, three split, or more complex states on Win10, Win11! This is completely wrong, even worse than not restore, so weird.

    On GNOME, most GNOME apps have size restore,but not position restore.

    Multi-monitor support has been the massive problem for all platforms, and if you store a position, it's best to judge whether it causes the window part to appear outside the monitor? Does it cause the coordinates to be negative (although allowed under windows, but not recommended)?

    Also, if the position is restored, is the monitor the window is on when it opens, the one the user wants? I'm not a dual-monitors user, but I've observed that they often run into the situation where they click on an icon on monitor A, and the window appears on monitor B, and they have to drag it back. Of course, desktop environments have a tricky way around this problem by only showing the taskbar, dock, or whatever on the primary monitor, which ensures that you can only click on an icon to launch an application on the primary monitor, and then, to launch the application only on the primary monitor, you just need to eliminate the need to memorize the location of the window on the secondary monitor... So why not just drop the store?

    More and more people are using cross-platform GUI these days, but much of the above requires native code to provide support. This would be a disaster for most mediocre app development teams, I'm afraid, and how do you anticipate that more relevant features will be added to the desktop environment afterwards? Will your old apps look so out of place in the new environment that the user experience is not as good as not adapting?

    To summarize, here I give the simplest, robust, but not full featured approach: Restore window size, reset after scaling or resolution change, restore maximized state, no restore window position and split-screen state.

    Where to store?

    Most projects writes to a config file and reads it at startup. For example https://github.com/mawie81/electron-window-state . Some projects under Linux write to dconf, some projects under windows use the Registry, but if we look at it from a cross-platform point of view, it's probably safer and more consistent to use a config file instead of windows registry / Linux dconf. Besides, some Linux desktop environments don't have dconf.

  22. felixrieseberg commented on Jan 17, 2025

    @felixrieseberg
    Member

    Hey everyone! Thank you all so much for giving Electron a try and thinking about ways to make it better. As you can probably tell from how this issue has been open for more than ten years, so far it has never been important enough for someone to close it directly or to otherwise make the resources available for it to happen.

    If you're wondering what you can do to get this into Electron, great news - Electron is truly open source! We, the maintainers, welcome outside contributions - especially from individuals and companies interested in joining us in maintaining this platform.

    If you're reading this and are thinking to yourself "Alright, I'll do it!" - good for you! For smaller changes, you can usually open a well-tested and documented PR directly on this repository. For larger changes, I'd recommend that you start with a "request for comments". This will ensure that you don't spend a lot of time on a larger change without getting feedback about your approach first. Alternatively, you could always hire a consultant, either from the maintainer community our outside, to perform the work that's important to you.

    In short, I'm closing this issue because we're currently not planning this work, but if you care deeply about this issue, we'd welcome your contribution.

  23. added a commit that references this issue on Oct 6, 2025
  24. citelao commented on May 6, 2026

    @citelao

    Adding onto the list of caveats for anyone who delves into this, while I was on the Windows team at Microsoft, I worked with @ekoschik to open-source some of his guidelines and sample code on remembering window positions on Windows (including an extensive README, also further some further revisions). Unfortunately, I was not able to get the PR into a state I was comfortable with before I left, and my priorities are different at my new job 😄 .

    I hope this helps, and thank you to anyone who moves this forward!

  25. wesleydarnell commented on May 15, 2026

    @wesleydarnell

    I dream of official support for this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions