Search code examples
javascriptnode.jspuppeteerwebautomation

Connect to currently active tab in Chrome with puppeteer-core


I am using puppeteer-core and connect to my own chrome installation. That works fine, but how can I execute commands on the currently active tab? how to get a reference to it?

const wsChromeEndpointurl = 'ws://127.0.0.1:9222/devtools/browser/12345';
const browser = await puppeteer.connect({
    browserWSEndpoint: wsChromeEndpointurl
});

const page = <active tab> // what do I need here?

(My goal is to do some things like logging in to a website manually, then let puppeteer take over. So I really want to use puppeteer-core)


Solution

  • There is no direct API to solve this but you can iterate through the pages array and evaluate the visibilityState property of the document.

    async function activePage() {
      const allPages = await context.pages();
      for(let page of allPages) {
        const state = await page.evaluate(() => document.visibilityState);
        if(state === 'visible') {
          return page;
        }
      } 
    }