'Button click event binding in playwright function in a new window electron js

I am new to electron and other front-end technologies. I am trying to implement a desktop app using electron. In this app on clicking a button "Run Playwright" a new window should open and run the playwright function in this new window!

I used below HTML code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Buyer-Assistant</title>
</head>

<body>
    <h1>Hello World!</h1>
    <button type="submit" id="btnEd" value="run playwright" >Run Playwright</button>
</body>
</html>

following the electron documentation!

main.js

const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration:true,
      contextIsolation: false,
      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()
  }
})

electron preload! preload.js

window.addEventListener('DOMContentLoaded', () => {
    const replaceText = (selector, text) => {
      const element = document.getElementById(selector)
      if (element) element.innerText = text
    }
  
    for (const type of ['chrome', 'node', 'electron']) {
      replaceText(`${type}-version`, process.versions[type])
    }
  })

by clicking on the button call this function in a new window playwright.js

const { _electron: electron } = require('playwright');

async function runPlaywright() {
  // Launch Electron app.
  const electronApp = await electron.launch({
    args: ['main.js']
  });

  // Get the first window that the app opens, wait if necessary.
  const window = await electronApp.firstWindow();

  // Capture a screenshot.
  await window.goto('http://whatsmyuseragent.org/');
  await window.screenshot({ path: 'intro.png' });

  // Exit app.
  await electronApp.close();
};



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source