How to get the screen width and height in Electron Framework

How to get the screen width and height in Electron Framework

Tipically, the screen object contains information about the user screen in the Browser. There is no public standard that applies to the screen object, however all major browsers support it.

So we would use the following snippet to retrieve the dimensions of the screen using Javascript in the Browser:

var monitorWidth = screen.width;
var monitorHeight = screen.height;

console.log(monitorWidth + "x" + monitorHeight);
// Outputs i.e : 1280x720

However, this doesn't work in Electron. In this article, you'll learn why this variable doesn't work as it should and how to retrieve these values properly.

The screen variable in Electron

The only and simple reason why screen is not available with the default properties that we see and handle in a normal browser, is that screen is an EventEmitter. Both in the renderer and DevTools, window.screen is a reserved DOM property, so replacing it (writing let {screen} = require('electron')) will not work.

Get screen(s) dimensions

Instead of accessing the screen global variable in the browser, we need the screen variable available in the Electron constant which you can retrieve using:

const electron = require('electron');
var screenElectron = electron.screen;

The screen object will grant you access to information about the screen (or the screens in case you have more than one):

var mainScreen = screenElectron.getPrimaryDisplay();
var allScreens = screenElectron.getAllDisplays();

console.log(mainScreen, allScreens);

The getPrimaryDisplay method (or every object in the array returned by the getAllDisplays method) will have a structure similar to:

Screen information Electron

You can read more about the screen module in the documentation of Electron here.

In order to retrieve the height and width of the screen, you can rely on the size property of the returned screen object:

var mainScreen = screenElectron.getPrimaryDisplay();
var dimensions = mainScreen.size;

console.log(dimensions.width + "x" + dimensions.height);
// Outputs i.e : 1280x720

The retrieven object (with the mainScreen method) provides more information about the dimension and other properties of the screen:

  • workAreaSize: provides the dimensions (height and width) of the screen without the taskbar height.
  • touchSupport: specifies in a string if the screen uses touch technologies.
  • scaleFactor: returns the scale factor of the screen (Float) in case it has (1 will be the default value for any screen without zoom enabled).
  • rotation: specifies if the screen orientation is different to 0 (normal).

Have fun !

Become a more social person