How to perform clicks in BrowserWindow of an Electron app?

I am writing and Electron app. It has a main browser window. Then from there I open another BrowserWindow. Now I want to programmatically click on a button that is present on the child browser window. How can I achieve that ?

Let’s assume that my code in the render process of the main window is as follows :

const childWindow = new BrowserWindow({
        width: 800,
        height: 600,
    })
childWindow.loadUrl('...')
// wait for the window to settle
setTimeout(()=>{
    // the code to click the button
}, 3000)


Answer

You can make use of preloads, which are basically scripts that run inside an Electron browser window

const childWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
        preload: path.join(/* path to preload script*/),
        contextIsolation: false,
        enableRemoteModule: true
    }
})
childWindow.loadUrl('...')

// my preload script

document.addEventListener('DOMContentLoaded', () => {
    //get your element using getElementById or querySelector.. etc
    // then perform the .click() on that element
});