Published on

How to get Active Page in Google Puppeteer

Authors

If you're working with a lot of pages and want to get the active page in Google Puppeteer, here's how to do it using visibilityState.

// reference: https://github.com/puppeteer/puppeteer/issues/443
export async function getActivePage(browser, timeout) {
    const start = new Date().getTime();
    while (new Date().getTime() - start < timeout) {
        const pages = await browser.pages();
        const arr = [];
        for (const p of pages) {
            if (await p.evaluate(() => { return document.visibilityState == 'visible' })) {
                arr.push(p);
            }
        }
        if (arr.length == 1) return arr[0];
    }
    throw "Unable to get active page";
}

Happy finding page!