How to Handle iFrames, Tabs and Windows | Playwright TypeScript Tutorial | X | LambdaTest

:rocket: Hello Testers!

Our new tutorial is live! :tada: Dive into ‘How to Handle iFrames, Tabs, and Windows’ with Playwright & TypeScript. :desktop_computer:

Learn essential tips, tricks, and techniques to master these complex elements in your test automation journey.

:point_right: Watch it now and level up your skills:

Handling iFrames Using frameLocator() Playwright provides frameLocator() to interact with elements inside an iFrame without switching context manually.

import { test, expect } from '@playwright/test';

test('Handle iFrame using frameLocator', async ({ page }) => {
  await page.goto('https://example.com');

  // Locate the iFrame
  const frame = page.frameLocator('#iframeID');

  // Interact with elements inside the iFrame
  await frame.locator('button#submit').click();
  await expect(frame.locator('h1')).toHaveText('Success');
});

:white_check_mark: This method avoids manual frame switching and allows direct interaction with elements inside the iFrame.

To work with multiple tabs, Playwright allows opening a new page via context.newPage().

import { test, expect } from '@playwright/test';

test('Handle multiple tabs', async ({ context, page }) => {
  await page.goto('https://example.com');

  // Open a new tab
  const newPage = await context.newPage();
  await newPage.goto('https://example2.com');

  // Perform actions in the new tab
  await newPage.locator('input#search').fill('Playwright');
  await newPage.locator('button#searchButton').click();

  // Switch back to the original tab
  await page.bringToFront();
  await expect(page).toHaveTitle(/Example Domain/);
});

:white_check_mark: This method ensures independent tab interaction while keeping control of both pages.

When an action triggers a new window, Playwright provides event listeners like page.waitForEvent(‘popup’) to capture and control the new window.

import { test, expect } from '@playwright/test';

test('Handle new window using event listener', async ({ page }) => {
  await page.goto('https://example.com');

  // Click a link that opens a new window
  const [newWindow] = await Promise.all([
    page.waitForEvent('popup'), // Capture the new window event
    page.locator('a[target="_blank"]').click(),
  ]);

  // Switch to the new window and verify the title
  await newWindow.waitForLoadState();
  await expect(newWindow).toHaveTitle(/New Window/);
});

:white_check_mark: This method efficiently waits for dynamically opened windows and interacts with them seamlessly.