Puppeteer randomly opens a new window in loop

Viewed 13

I'm pretty new to puppeteer. I wrote something like this to help me answer hundreds of questions everyday. The problem is the code works fine on the first run but then when it gets back to the beginning of the loop it clicks on the first conversation and it opens it in a new browser window. Then it continues going in the previous window. What can be causing this? There is no option there to even open the conversion in a new window. Basically every pass through it opens a new window for each conversation when it clicks that element.

const puppeteer = require('puppeteer');

(async () => {

    const browser = await puppeteer.launch({
        headless: false,
        executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe',
        ignoreDefaultArgs: true,
        args: [
            '--remote-debugging-port=9444',
            '--user-data-dir=D:/chrome-profiles/toys',
            '--no-first-run',
            '--no-default-browser-check',
            `--window-size=1920,1080`
        ]
    });

    await new Promise(r => setTimeout(r, 2000));


    const pages = await browser.pages();
    const page = pages[0];
    const line1 = 'Hello,'
    const line2 = "This product will be available again in 2 days. There will be a notification on our page when it's back in stock."

    await page.goto('https://www.facebook.com/messages/t/');

    await new Promise(r => setTimeout(r, 2000));

    await page.waitForSelector('.o7bt71qk:nth-child(2)').then(selector => selector.click());

    for (let i = 0; i <= 50; i++) {

        //click first message
        await page.waitForSelector('div:nth-child(1) > .b0eko5f3 > div > .qi72231t').then(selector => selector.click());
        await new Promise(r => setTimeout(r, 1000));

        //type message
        await page.waitForSelector('[aria-label="Message"]').then(selector => selector.click());
        await new Promise(r => setTimeout(r, 1000));
        await page.type('[aria-label="Message"]', line1, { delay: 5 });
        await page.keyboard.down("ShiftRight")
        await page.keyboard.down("Enter")
        await page.keyboard.down("Enter")
        await page.type('[aria-label="Message"]', line2, { delay: 5 });
        await page.keyboard.down("ShiftRight")
        await page.keyboard.down("Enter")
        await page.keyboard.down("Enter")
        
        //Send Message
        await page.waitForSelector('.c7y9u1f0 > .db0glzta').then(selector => selector.click());
        await new Promise(r => setTimeout(r, 2000));
 
        //delete chat
        await page.waitForSelector('.qtx5e3l4 > .b6ax4al1').then(selector => selector.click());
        await new Promise(r => setTimeout(r, 2000));
    }
})();
0 Answers
Related