Search code examples
playwrightplaywright-testplaywright-typescript

Playwright: Unable to capture URL address of a new tab in headless mode


The test fails in headless mode, but when mode is headless: false test passed.

await productAttachment.element.click();    // this action opens a new page with a pdf attachment

const newPage = await page.waitForEvent('popup');
await expect(newPage).toHaveURL(expectedAddressURL);

I also tried using the version with:

await context.waitForEvent('page');

but it behaves the same.

I have already tried many solutions but nothing helps.

Logs:


Received string: "about:blank"
    Call log:
      - expect.toHaveURL with timeout 10000ms
      - waiting for locator(':root')
      -   locator resolved to <html>…</html>
      -   unexpected value "about:blank"

Environment:

  • @playwright/test: ^1.44.0
  • Operating System: Windows
  • Node.js version: v20.12.2
  • Browser: chromium

Solution

  • Handling pdf in headed and headless need different approaches see https://github.com/microsoft/playwright/issues/6342

    Below is example test. Remember to set consts.

    import { expect, test } from '@playwright/test';
    
    const url = ;
    const linkToPdf = ;
    const pdfUrl = ;
    
    test('verify link in new tab in headless', async ({ page, browserName, headless, context }) => {
        await page.goto(url);
        await page.locator(linkToPdf).first().click();
       
        // start waiting for new tab
        const newTabPromise = page.waitForEvent('popup');
    
        // check if browser is chromium and headless is true and handle it
        // https://github.com/microsoft/playwright/issues/6342
        if (browserName === 'chromium' && headless === true) {
            const [download] = await Promise.all([
                page.waitForEvent('download'), // wait for download to start
                page.getByLabel('fileName').click(),
            ]);
            const endsWithPdf = download.suggestedFilename().endsWith('.pdf');
            expect(endsWithPdf).toBe(true);
        }
        else if ((browserName === 'chromium' && headless === false) || browserName === 'firefox' || browserName === 'webkit') {
            await page.getByLabel('fileName').click();
            const newTab = await newTabPromise;
            newTab.on('response', response =>
                expect(response.headers()['content-type']).toBe('application/pdf')
            );
            await newTab.waitForURL(pdfUrl);
        }
    
    });