The script below needs to connect to an already open instance of Google Chrome because I am already logged in there with my username and password. If it opens a new one, it will need to log in again, and the environment requires two-factor authentication. Therefore, the ideal solution is to use the one that is already open. So far so good.
The only thing I need now is to ensure that it does not maximize every time the script runs, since it is a script that will run in a loop until I stop it manually or if it encounters an error.
const puppeteer = require('puppeteer');
const requests = '<my_url>'
let browser;
async function startbrowser() {
if (!browser) {
browser = await puppeteer.connect({
browserWSEndpoint: 'ws://127.0.0.1:9222/devtools/browser/<my_address>',
});
}
return browser;
}
async function monitor() {
try {
await startbrowser();
const page = await browser.newPage();
await page.goto(requests, { waitUntil: 'networkidle0' });
const frame = await page.frames().find(f => f.name() === '<frame_name>');
if (!frame) {
console.log('Frame not found');
return;
}
const noRecords = await frame.evaluate(() => document.body.innerText.includes("No records"));
if (noRecords) {
console.log("No records to display found, script will run again after 3 minutes");
await page.close();
setTimeout(() => monitor().catch(console.error), 180000); //3min
} else {
console.log("Records found, proceeding with actions.");
const coordinates = await frame.evaluate(() => {
const el = document.body;
const {x, y} = el.getBoundingClientRect();
return {x, y};
});
await page.mouse.click(coordinates.x + 80, coordinates.y + 240, { button: 'right' });
await page.mouse.move(coordinates.x + 120, coordinates.y + 300);
await page.mouse.click(coordinates.x + 120, coordinates.y + 300, { button: 'left' });
await page.close();
}
} catch (error) {
console.error("An error occurred:", error);
} finally {
setTimeout(() => monitor().catch(console.error), 10000); //10s
console.log("waiting 3 minutes to run again");
}
}
monitor().catch(console.error);
I tried running the code above, but every time it runs, the Chrome windows are maximized.