3

I'm just starting to play with Electron today. I need to be able to get the available window size, and to update it on the window resize.

It seems that this isn't as simple as it is in a conventional JS app. What's the recommended way for keeping track of the window size?

At the moment, I have my main process and a single renderer, with no plans to have more than 1 renderer/window open at a time.

I have tried to use the following, but it seems completely wrong so I must have misunderstood the docs.

const {BrowserWindow} = require('electron').remote
BrowserWindow.getSize()

EDIT:

Is it reasonable to keep track of the height by watching the body of the app? I can set this to 100% width/height and watch it, but it seems a bit of a hack.

Thanks Tom

tom_h
  • 876
  • 2
  • 9
  • 15
  • 1
    by "the available window size" do you mean the size of your physical display? Otherwise, `getSize()` should work, but you must call it on a `BrowserWindow` _instance_ not as static function – pergy May 17 '17 at 07:00
  • Thanks, that makes sense. I should have been a bit clearer on that, I actually want to know the size of the current app window (I guess this would be the renderer)? What I need to be able to do is use the size of the current available height to determine the size of something else. Unfortunately it needs to be done in pixels rather than percentages. – tom_h May 17 '17 at 14:42
  • your current app window is probably also a `BrowserWindow`. If you have no variable of it, you can retrieve it by `BrowserWindow.getFocusedWindow()` or choose from `BrowserWindow.getAllWindows()` static functions, then use `getSize` on instance. Also you may want to listen to its `'resize'` event. Take a look at the [api docs](https://electron.atom.io/docs/api/browser-window/) – pergy May 18 '17 at 06:38

2 Answers2

8

you can try

const electron = require('electron')
const remote = electron.remote

remote.getCurrentWindow().webContents.getOwnerBrowserWindow().getBounds()

Bounds will have co-ordinate and size of current window,

{ 
  height: 1040,
  width : 837,
  x : 276,
  y : 78 
}
alexander.polomodov
  • 5,396
  • 14
  • 39
  • 46
manirikhi
  • 129
  • 1
  • 5
5

This works in v4.0.4:

in renderer.js:

import { remote } from "electron";

console.log('size:', remote.getCurrentWindow().getSize());
// size: [1000, 700]

console.log('bounds:', remote.getCurrentWindow().getBounds());
// bounds: {height: 700, width: 1000, x: 226, y: 97}

in main.js:

import { BrowserWindow } from "electron";

let mainWindow: BrowserWindow

// ...after mainWindow is created
console.log('size:', mainWindow.getSize());
console.log('bounds:', mainWindow.getBounds());
Nemi
  • 1,012
  • 10
  • 19