How to extract page title from a new tab using puppeteer

I’m working on a web scraping project where I need to click a link that opens in a new tab, then get the title from that newly opened tab using puppeteer.

Here’s my current code:

const puppeteer = require('puppeteer');

const delay_time = 2000;

async function scrapeTitle() {
    const browser = await puppeteer.launch({
        headless: false
    });
    const mainPage = await browser.newPage();
    
    await mainPage.goto('https://example-blog.com/article/mixed-models-guide/');
    
    const linkSelector = '#article-123 > div > section.content > p:nth-child(3) > a:nth-child(1)';
    
    await mainPage.waitFor(delay_time);
    await mainPage.click(linkSelector);
    
    // After clicking, a new tab opens
    let allPages = await browser.pages();
    
    // Need to switch to the new tab and get its title
    // This is where I'm stuck
    
}

scrapeTitle();

The issue I’m having is figuring out how to properly access the newly created tab after clicking the link. I know I need to use the pages array but I’m not sure how to target the specific new page and extract its title. The new tab should contain a page with the title ‘Advanced Mixed Models Tutorial’ but I can’t seem to access it properly.

Instead of polling the pages array, listen for the new page creation event. Add browser.on('targetcreated', async (target) => { ... }) before clicking the link - this catches the new tab right when it opens. In the event handler, grab the page with await target.page() and extract the title using await newPage.title(). This method’s way more reliable than checking pages length since it handles timing automatically and you don’t have to guess which page is new.

Wait for the new tab to fully load before interacting with it. After clicking the link, let the page get created then make sure it’s loaded completely. Use page.waitForLoadState() or page.waitForSelector() to check the content’s ready. I had the same timing issues with popups - adding these wait conditions fixed everything. The browser needs time to initialize the new tab once it shows up in the pages array.

Grab the last page from the array - new tabs usually get added at the end. Use let newTab = allPages[allPages.length - 1]; then await newTab.title() for the title. This worked for me on similar scraping projects. Just wait a sec after clicking so the tab loads first.