Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening new Window - Electron

Tags:

electron

I'm currently trying to implement a new Window on my Electron App. So I want to include a button, and when you click on this Button, a new Window should be opened. I didn't find anything in the Electron documentation, maybe one of you can help me.

like image 892
Boby Avatar asked Nov 20 '18 10:11

Boby


2 Answers

Perhaps something like this:

const button = document.getElementById('<your_button_id>');
button.addEventListener('click', () => {
  createBrowserWindow();
});

function createBrowserWindow() {
  const remote = require('electron').remote;
  const BrowserWindow = remote.BrowserWindow;
  const win = new BrowserWindow({
    height: 600,
    width: 800
  });

  win.loadURL('<url>');
}
like image 194
Nishkal Kashyap Avatar answered Oct 17 '22 17:10

Nishkal Kashyap


I believe the answer that has been taken as correct is outdated. I have managed to do it with the ipc module and with the solution given by Nishkal. Please, read the ipc module, I'm new to electron and not very experienced with programming. I'm sure you can come with better solutions. Code I added in order for it to work:

my main.js

const {app, BrowserWindow} = require('electron');
const path = require('path');

//ipc
const { ipcMain } = require('electron')
ipcMain.on('asynchronous-message', (event, arg) => {
  createWindow();
})

const createWindow = () => {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
        },
        
    });

    win.loadFile('index.html');
}

app.whenReady().then(() => {
    createWindow();

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    })
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit();
})

my preload.js

 window.addEventListener('DOMContentLoaded', () => {
        const { ipcRenderer } = require('electron')
        ipcRenderer.on('asynchronous-reply', (event, arg) => {
            console.log(arg) // prints "pong"
          })
        //button and its event listener
        const b1 = document.getElementById('b1');
        b1.addEventListener('click', () => {
            ipcRenderer.send('asynchronous-message', 'ping')
        })
      })
like image 34
David Nichero Avatar answered Oct 17 '22 18:10

David Nichero