Position BrowserWindow to right side of screen?


#1

Hey everyone,

I am trying to create a new Browser Window and have it be positioned on the far right side of the screen sort of docked there. The problem is that monitor resolution and sizes can change and setting a static x/y value isn’t going to work for me. I have tried electron-positioner but it seems out of date and can’t get it work.

Thanks for any help or guidance you may have.


#2

Hey,

You can use the screen API (https://electronjs.org/docs/api/screen) to do this. All you need to do is get the bounds of the display (you can loop through each screen and get the display width to calculate multiple displays) and then set the x position of your app to the full width minus the width of your app.

I use the same concept to stop my app being dragged off the edge of the display (or moving it if the display changes in any way).

Something like:

let screen = electron.screen;
let displays = screen.getAllDisplays();
let width;
for(var i in displays)
{

	width+= displays[i].bounds.width;

}

width now stores the full width of the display. Subtract the width of your app from that and you’ve got your x position.


#3

Hey,

Thanks so much! I was able to get it to work perfectly.

Cheers


#4

I guess I spoke too soon and followed the documentation too closely. I was able to get it work following the external display example, but it only works when I have external displays (makes sense).

How would I use this width value to set the x position on a new BrowserWindow? Something like this?

createWindow.addEventListener('click', function (event) {
    let displays = electron.screen.getAllDisplays()
    let width;
    for(var i in displays){
        width+=displays[i].bounds.width;
   }
    const {
        remote
    } = require('electron')
    remote.BrowserWindow.getFocusedWindow().minimize();
    infoModal = new BrowserWindow({
        x: width - 600,
    });

Thanks again. I feel close but stumped.


#5

Yes, but you should set ‘y’ position as well.

see more info in https://github.com/electron/electron/blob/master/docs/api/browser-window.md#new-browserwindowoptions

x Integer (optional) (required if y is used) - Window’s left offset from screen. Default is to center the window.
y Integer (optional) (required if x is used) - Window’s top offset from screen. Default is to center the window.


#6

I got it to work, thanks for your guidance. Here is what I did

createModal.addEventListener('click', function (event) {
    let display = electron.screen.getPrimaryDisplay();
    let width = display.bounds.width;
infoModal = new BrowserWindow({
        height: 600,
        width: 600,
        x: width - 600,
        y: 0
    });