Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Window Positioning in Electron

I need to know how to open new windows which is offset a little by the current window position (first window will be opened in the center)

My codes are as follows:

// index.js

const {app,BrowserWindow,Menu,MenuItem,dialog}=require('electron');

function window_open(path){
  win = new BrowserWindow({show: false})
  win.loadURL(path);
  win.once('ready-to-show', () => {win.show()})
}


let win

app.on('ready',event=>{
  'use strict';
  window_open(`file://${__dirname}/index.html`)
});

This opens the initial window in the center. I am also passing this function in the new window command (cmd+n)

{
  label: 'File',
  submenu: [
    {label: 'New Window', accelerator: 'CmdOrCtrl+N', click: () => (
     window_open(`file://${__dirname}/index.html`))
},

The code works fine, except that every window is positioned the same, in the center. I would like each new windows to be offset a little.

What's the best way to achieve this?

like image 434
Joseph K. Avatar asked Mar 07 '23 17:03

Joseph K.


1 Answers

I learned that I need these two things:

  1. BrowserWindow.getFocusedWindow()
  2. win.getPosition()

Combining with @pergy's response, I got the following code which finds the focused window if there is any and offsets a new window from its position, otherwise creates a new window in the center:

let win = null;
function window_open(path) {
  const opts = { show: false };
  if (BrowserWindow.getFocusedWindow()) {
    current_win = BrowserWindow.getFocusedWindow();
    const pos = current_win.getPosition();
    Object.assign(opts, {
      x: pos[0] + 22,
      y: pos[1] + 22,
    });
  };
  win = new BrowserWindow(opts);
  win.loadURL(path);
  win.once('ready-to-show', () => { win.show() });
};

app.once('ready', event => {
  window_open(`file://${__dirname}/index.html`);
});

This does what I asked for in my original question, so I have decided to post this. However, I do feel that it is slow in spawning the new windows, so I won't mark this as an answer to see if there are faster approaches to this.


Update: I have found out that waiting on 'ready-to-show' is what makes it slow, as it waits for the ready state. I have accepted this as the answer as I feel that the speed issue is dependent to the content and not the browser. Feel free to add comments on this as I am still open ears.

like image 114
Joseph K. Avatar answered Mar 31 '23 07:03

Joseph K.