Trying to use WDIO in Electron app causes error

30 views Asked by At

I'm trying to run WDIO by clicking button in Electron app, but when I launch the app and click the button the app goes blank. i.e. It becomes a white screen. If I open DevTools before clicking it displays the following message:

"DevTools was disconected was diconected the page"

WDIO script works properly by itself, here it is:

const { remote } = require('webdriverio')
const fs = require('fs')
const path = require('path')
const axios = require('axios')

async function getData() {
    const dir = process.cwd() + '\\Download';
    const browser = await remote({

        capabilities: {
            browserName: 'chrome',
            'goog:chromeOptions': {
                args: ['--headless', '--window-size=900,700'],
                prefs: { "download.default_directory": dir }
            }
        }
    })
    // Opening the website
    await browser.url('https://somewebsite');
    await browser.pause(2000);
    // Enter login 
    let access = JSON.parse(fs.readFileSync('passwords.json'));
    await browser.$('input[name="LoginForm[username]"]').setValue(access.login);
    await browser.$('input[name="LoginForm[password]"]').setValue(access.password);
    await browser.$('//button[@class="btn btn-danger btn-block btn-lg"]').click();
    await browser.pause(2000);
    // Go through the website
    await browser.url('https://somewebsite');
    const table = await browser.$('/html/body/div[2]/div[1]/div[3]/div[2]/table');
    await browser.pause(2000);
    async function counts() {
        const count = await browser.$('/html/body/div[2]/div[1]/div[3]/div[2]/table/tfoot/tr/td[1]').getText();
        const textRemove = count.replace('Показано ', '').replace(' із ', ', ');
        return textRemove.split(',').map(Number);
    }
    let number = await counts();
    while (number[0] < number[1]) {
        await table.scrollIntoView({ block: 'end', inline: 'end' });
        await browser.pause(500);
        number = await counts();
    }
    await browser.$('/html/body/div[2]/div[1]/div[3]/div[1]/div[2]/div[2]/button').click();
    await browser.$('/html/body/div[2]/div[1]/div[3]/div[1]/div[2]/div[2]/div/div[2]/div[2]/a[4]').click();
    await browser.pause(3000);
    await browser.closeWindow();
    // Rename downloaded files
    const oldFiles = fs.readdirSync(dir);
    oldFiles.forEach((fileName) => {
        const currentFilePath = path.join(dir, fileName);
        // Check if the file's name contains the part you want to modify
        if (fileName.includes('Товари')) {
            // Create the new file name by replacing the part
            const newFileName = fileName.replace('Товари', 'Goods');
            // Construct the new file path
            const newFilePath = path.join(dir, newFileName);
            // Rename the file
            fs.renameSync(currentFilePath, newFilePath);
        }
    });
    // Check the location
    const files = fs.readdirSync(dir);
    const fileStats = files
        .map(file => ({
            name: file,
            path: path.join(dir, file),
            stats: fs.statSync(path.join(dir, file))
        }))
        .filter(file => file.stats.isFile());
    const lastFile = fileStats
        .sort((a, b) => b.stats.mtime - a.stats.mtime)[0];
    const lastFilePath = lastFile.path;
    // Send data to the JSON
    let data = JSON.parse(fs.readFileSync('links.json'));
    data.DNTrade = lastFilePath;
    const JSONData = JSON.stringify(data, null, 2);
    fs.writeFileSync('links.json', JSONData);
    console.log(fs.readFileSync('links.json') === JSONData);
    if (fs.readFileSync('links.json') === JSONData) {
        (await async function makePostRequest() {
            axios.post('http://127.0.0.1:5000', 'Data updated successfully')
                .then(function (response) {
                    console.log(response.data);
                })
                .catch(function (error) {
                    console.error('Error:', error);
                });
        }())
    }
};

window.addEventListener('DOMContentLoaded', () => {
    const button = document.querySelector('#butt');
    button.addEventListener('click', () => {
        getData()
    })
})

Here the 'index.html' file I use to render the page in Electron:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <button id="butt">Click me</button>
</body>
</html>

And finally 'main.js' which electron uses:

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

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

    mainWindow.loadFile('index.html')
    mainWindow.on('closed', function () {
        mainWindow = null;
    });
}

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

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

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

I've tried to launch WDIO in both Firefox and Edge by changing capabilities, but the issue remains the same. Initially, I used import in WDIO, but it was too confusing to integrate it into Electron. So, I switched to require and checked the WDIO script by itself. It still works, but inside Electron, it doesn't. When I enabled logging in main.js, I received only 'Renderer process crashed'. The only useful thing I found in other similar answers on Stack Overflow is logging and debugging, but I still hope there is an easier way

0

There are 0 answers