DEV Community

Takuya Matsuyama
Takuya Matsuyama

Posted on

How to check if a browser window is inside of screens on Electron

If your Electron app remembers the last window position and restores it on launch, it may cause an issue for those who have a secondary screen.
Because secondary screens can be detached in a certain situation, the window can be outside of the screen when restoring the position but the screen was not connected.
To detect this, you can check if a given position is inside of any of the screens like so:

import { remote, ipcRenderer, BrowserWindow } from 'electron'
const { screen } = remote

function isWithinDisplayBounds(pos: { x: number, y: number }) {
  const displays = screen.getAllDisplays()
  return displays.reduce((result, display) => {
    const area = display.workArea
    return (
      result ||
      (pos.x >= area.x &&
        pos.y >= area.y &&
        pos.x < area.x + area.width &&
        pos.y < area.y + area.height)
    )
  }, false)
}
Enter fullscreen mode Exit fullscreen mode

Then, if it's out of bounds, it should be moved into the primary screen:

const isOnScreen = isWithinDisplayBounds({ x, y })
const primaryScreenBounds = screen.getPrimaryDisplay().bounds
if (!isOnScreen) {
  x = (primaryScreenBounds.width - w) / 2
  y = (primaryScreenBounds.height - h) / 2
}
Enter fullscreen mode Exit fullscreen mode

Subscribe Newsletter

My YouTube channel

Top comments (0)