Playwright + TS · Lesson 22 of 36

0/36 done

Module 22: Frames, Windows & Popups

22. Seamless Handling of iFrames, Multi-Tabs & Native Dialogs

18 minlesson

Try it yourself

Implement isDialogAccepted:

  1. Verify if dialogType matches 'alert', 'confirm', or 'prompt'.
  2. Return true if valid, false otherwise.

The editor has a worked example. Read it, tweak it, then press Mark as complete.

1. The frameLocator() API

You don't need to 'switch' context into a frame and then 'switch back' to default content:

typescript
// Directly locate elements inside an iframe:
const paymentFrame = page.frameLocator("#stripe-payment-frame");

// Nested iframes are simply chained:
const nestedFrame = paymentFrame.frameLocator("#card-number-subframe");

// Execute actions directly inside the frame:
await nestedFrame.getByLabel("Card Number").fill("4242 4242 4242 4242");

2. Multi-Tab & New Window Handling

When a link opens a new tab via target="_blank":

typescript
// Start waiting for the new page event BEFORE clicking the link:
const pagePromise = context.waitForEvent("page");
await page.getByRole("link", { name: "Open Terms in New Tab" }).click();
const newPage = await pagePromise;

// Verify content in the new tab:
await newPage.waitForLoadState();
await expect(newPage).toHaveTitle(/Terms of Service/);

// Close the tab and return focus to main page:
await newPage.close();

3. Native JavaScript Dialogs (alert, confirm, prompt)

By default, Playwright automatically dismisses native dialogs so tests don't hang. To accept or verify dialog message:

typescript
page.on("dialog", async (dialog) => {
  console.log("Dialog message:", dialog.message());
  // Accept confirm dialog:
  await dialog.accept();
  // Or dismiss: await dialog.dismiss();
  // Or provide prompt input: await dialog.accept("My Input");
});

await page.getByRole("button", { name: "Delete Account" }).click();

Key Takeaways & Walkthrough Summary

Handling iframes and multiple tabs used to be a major pain point in older tools. In Playwright, frameLocator makes interacting with iframes seamless without manual context switching. In this lesson, we will cover iframes, nested frames, new browser tabs, and native alert and confirm dialogs. Let's explore how simple it can be!

Part of the Playwright + TS course (Playwright with TypeScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

What happens if a dialog opens and I don't register a page.on('dialog') listener?

Playwright will automatically dismiss the dialog so your test execution does not hang indefinitely.

Can frameLocator interact with cross-origin iframes?

Yes! Unlike browser JavaScript, Playwright's automation protocol is out-of-process and has full access to cross-origin iframes.

Finished reading?

Review the worked example in the editor, then mark the lesson complete.

TypeScript
Skip