0

So I have an application where I create new window on button click. And now I would like to add some event listener on that new window (to write something in console), but it just does not work. How can I trigger that event listener on a new window, after new window is created on button click?

My code from one of js files:

const { BrowserWindow } = require('@electron/remote')
const remote = require('@electron/remote/main')

//Creating new window

let secondWindow = new BrowserWindow({
  kiosk:false,
  frame:true,
  show:false,


})

// On mouse click on main window show new window (secondWindow)

window.addEventListener('mousedown', function(event) {
  
  secondWindow.show();
  secondWindow.focus();
  secondWindow.webContents.openDevTools()


})

// And now i can't do this:
secondWindow.addEventListener('mousedown', function(event) {
  
  console.log('Second window click')


})
cofitigar
  • 3
  • 2
  • Can you provide some code? Something you have already done. Otherwise this question will likely be closed. – mat.hudak Jun 13 '22 at 10:52
  • Does this answer your question? [Using console.log() in Electron app](https://stackoverflow.com/questions/31759367/using-console-log-in-electron-app) – RickN Jun 14 '22 at 09:44
  • DOM events can’t be created in Electron's the main process, only in render process(es). If you need an event lister in your HTML file, include it in a script after your closing

    tag. If you need an action triggered by IPC once the window is loaded, use window.webContents.send(channel, ..args) immediately after [window.loadFile(filePath[, options])](electronjs.org/docs/latest/api/…). Add more information to your question for a refined answer. Plus, try not to use Electron remote if you can help it. Look for other ways to implement your functionality instead of using remote.

    – midnight-coding Jun 16 '22 at 11:03

1 Answers1

0

As per the documentation, you should make sure that the BrowserWindow is ready before you attach the event listener to it.

If the BrowserWindow is not ready you will be trying to attach an event to an undefined container.

Check the docs for more infos

const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ show: false })
win.once('ready-to-show', () => {
    win.show()
    // attach your event here
})