Playwright Tutorial: Handling Frames and Windows

  • Learning Hub
  • Playwright Tutorial: Handling Frames and Windows

OVERVIEW

Frames and windows are usually used to display 3rd party content or embed new pages within the range of a web page. In the world of automation testing, working with iframes in Selenium can be difficult because of the need to switch the context between the frame and the default context. The Playwright framework offers an alternative to managing and changing contexts by making it simple and intuitive.

This Playwright testing series covers many topics, such as features, handling inputs, buttons, alerts, dropdowns, frames, fixtures, etc. However, in this tutorial, we will discuss handling frames and windows in Playwright. You will also learn about the different types of frames, parent frames, windows, and multiple windows, with the help of live examples.

So, let’s get started!

You can also go through the following video from the LambdaTest YouTube Channel to learn more about handling frames and windows in Playwright.

Let’s look at the above modules one by one!

...

What is a Frame in Playwright?

A frame is an iframe that is part of a page. The frame can let you create a new experience inside the page. These new experiences are then accessible through interactions with the page.

Every time a page loads, the page displays the current frame tree using the frame.childFrames() and mainFrame() methods.

Three events that are issued on the page object regulate the lifecycle of the frame object: page.on('frameattached') - A frame can get attached to a page only once. page.on('framenavigated') - A frame navigates to different URLs. page.on('framedetached') - A frame gets detached from the page only once.

Let’s understand the frame in detail with a test scenario, as mentioned below:

Test Scenario:

Let’s use https://letcode.in/frame to explain handling farmers and windows in Playwright in detail. If you inspect the page, you can view the HTML tag, which also comes with the number of times it exists on the web page.

web page letcode

Procedure:

  • In the VS Code, create a test file and name it “frames.test.ts.” Within the file, you need to import the “expect” and “test” from the “@playwright/test.”
  • You will also have a test block called “Interact with frames.”
  • Next, navigate to the website.
  • When you inspect a page, you can view the number of frames on that page. However, the number of frames can change if you consider frequent advertisements. So, let’s enter an approximate value in the VS Code.
  • Execute the test in VS Code, and you can view the same in a different browser.
 VS Code procedure

There are two ways to view the test report.

  • You can view the test under Playwright reports, where you can see the HTML report. Click on the “stdout.” You can also see the number of frames.
  • Playwright HTML report
  • You can also view the output directly in the console. Use the “playwright.config.ts” to enable the test match by providing a test name. We will also configure the test in the “package.json” file. Next, bring up the terminal and execute the test script. The number of frames will appear in this test script.
  • playwright test script
LambdaTest

How to interact with Frames in Playwright?

A page can have one or more frame objects attached to the iframe HTML tag. Each page has a main frame and page-level interactions like “click” that are assumed to work within the main frame.

The iframe HTML tag allows for the attachment of additional frames to a page. For interactions within the frame, one can access these frames.

Frame Objects - One can obtain frame objects using the page.frame() API:

Test Scenario:

In this tutorial on handling frames and windows in Playwright, use the https://letcode.in/frame page for a demo. Consider the terms “first name” and “last name.”

  • Use the inspector to find the frame where “first name” and “last name” exist with the help of the locator. You can learn more about locators through this tutorial on locators.
  • Once you mouse hover, you can see the entire frame highlighted in blue.
tutorial on locators

Now let’s see how to interact with frames in the VS Code.

Procedure:

  • Type “page.frame()”; you also need to provide the “frame name”. For this, mouse hover and select from the available options. In this case, you need to use the frame's name. Copy the “first name” from the inspector.
  • Next, use the “fill” function to pass the locator and actual test data.
  • When a frame isn't available, consider using a function called “null” in the VS Code. You will notice a “?.” in the code, as shown in the below image. Use this symbol to check if the frame exists or not. The “fill” function occurs only when the frame does not show null. If not, the fill function does not happen.
  • letcode in optional chaining
    GitHub

    An alternative code for “?.” is the “if” function. You can use the “if” function to continue the test process.

     alternative code for letcode
  • Inspect the “last name” and use the “fill” function to pass the locator and test data.
  • Let's execute the test; you can see that the browser shows the test data. Hence you can conclude that the test has run successfully.

Frame locator in Playwright

When you need to test iframes, you can also use a frame locator to retrieve the iframe and locate elements within it. Frame locator helps you in finding the frame.

test("Interact with frames", async ({ page }) => {
 
 await page.goto("https://letcode.in/frame");
 const allframes = page.frames();
 console.log("No.of frames: " + allframes.length);

 const frame = page.frameLocator("#firstFr")
 await frame.locator("input[name='fname']").fill("Koushik");
 await frame.locator("input[name='lname']").fill("Chatterjee");

Procedure:

  • In the VS Code, do not use a name or URL; instead, use the id from the inspector.
  • Frame locator provides an option to interact with frames that are either; first, last or nth.
  • Next, use the fill function to pass the locator and actual test data.
  • Let's execute the test; you can see that the browser shows the test data. Therefore, you can conclude that the test has run successfully.

Nested Frames in Playwright

Fragmentation in browsers

Multiple frames within the parent frame are called Nested frames. The word "nested frame" indicates a frame inside another frame. Framesets may be nested to any level. More flexibility and complexity are available for page layout with nesting than with just dividing a frameset into a grid of rows and columns.

import { expect, test } from "@playwright/test";
 
 test("Interact with frames", async ({ page }) => {
  
     await page.goto("https://letcode.in/frame");
     const allframes = page.frames();
     console.log("No.of frames: " + allframes.length);
  
     const frame = page.frameLocator("#firstFr")
     await frame.locator("input[name='fname']").fill("Koushik");
     await frame.locator("input[name='lname']").fill("Chatterjee");
  
     const innerFrame = frame.frameLocator("iframe[src='innerFrame']")
     await innerFrame.locator("input[name='email']").fill("koushik@gmail.com")
  
     await frame.locator("input[name='fname']").fill("letcode");
  
     // const myFrame = page.frame("firstFr")
     // // if (myFrame != null) {
     // //     await myFrame.fill("", "")
     // // }
     // await myFrame?.fill("input[name='fname']", "koushik")
     // await myFrame?.fill("input[name='lname']", "chatterjee")
  
     // expect(await myFrame?.locator("p.has-text-info").textContent()).toContain("You have entered")
  
  
     await page.waitForTimeout(3000);
 

Now let us see how to interact with inner frames/nested frames in Playwright.

Procedure:

  • Let us inspect the https://letcode.in/frame page by searching for “iframe[src=’innerFrame’] and the locator.
  • Copy this code into the VS Code.
  • Use the frame locator to find the inner frames and enter the “fill” function by adding input and name.
  • Execute the test, and you can see the test generation in the browser. Thus, the test has run successfully.
  • It aids in identifying unknown areas in test scenarios, enhancing the product's immunity.
  • The testers can freely explore the program according to their intuition and comprehension. They can then run the tests as they go, assisting them in identifying mistakes as they go.
nested frames with Playwright

How to handle windows in Playwright?

Window handling in Playwright is simple. Each browser can have multiple pages. A Page refers to a single tab or a popup window within a browser context. You can use it to navigate URLs and interact with the page content.

Using the expect_page method, you can act on a new window or wait for it to load. Once present, use Playwright's assertion library to ensure that our user journey is successful.

...

Handling Tabs in Playwright

Let’s use the LambdaTest’s Selenium Playground (A demo page) to show a live example of the test scenario.

Test Scenario:

  • Open the demo page; you can see the title “Window popup Modal Example for Automation''. Within this title, there's an option that says “Single Window Popup” and “Multiple Window Modal''.
  • Under “Single Window Popup,” click on “Follow on Twitter.” The browser will bring up a pop-up, tab, or window ( all three options mean the same ). You will see the following image:
  • Follow on Twitter
  • The next step is to inspect the “Follow on Twitter” option. Use the link text that’s available under “XPath.”
  • await page.goto("https://www.lambdatest.com/selenium-playground/window-popup-modal-demo");
    console.log(page.url());
    const [newWindow] = await Promise.all([
        page.waitforEvent("popup"),
        page.click("'Follow On Twitter'")
    ]);
     
    console.log(newWindow.url());

Procedure:

Create a file with the name “windows.test.ts” in the VS Code. Next, go to your “playwright.config.ts” file and change the file name to “windows.test.ts.”

  • Under the “windows.test.ts” file, navigate to https://www.lambdatest.com/selenium-playground/window-popup-modal-demo. In Playwright, you can obtain interaction directly by using the window handles.
  • To perform multiple actions (for example - popup and element), use the “promise.all” function. This function comes into the scenario when you need to perform simultaneous actions.
  • Here, you need to perform two tasks. The first one is “waitforEvent,” which is a pop-up. Followed by a function called “click,” which opens up the “Follow on Twitter” element.

  • Next, use the “console.log” to print the new tab URL and the page URL.
  • Bring up the terminal and run the test. You can view the test actions as per the code script. Hence the test has run successfully.

Handling multiple Windows in Playwright

Let’s use LambdaTest’s Selenium Playground to show a live example of the test scenario.

Test Scenario:

  • Open the demo page; you can see the title “Window popup Modal Example for Automation''. Within this title, there's an option that says “Multiple Window Modal.” Click on the option that says “Follow Twitter & Facebook.” You can see two new tabs open in the image below.
  • Window popup Modal Example for Automation
  • Let’s see how to interact with the two new tabs. Open the inspector window, find the locate, and the id says “followboth.” Copy this id to the VS Code.
  •    const [multiPage] = await Promise.all([
            page.waitForEvent("popup"),
            page.click("#followboth")
        ])
        await multiPage.waitForLoadState();
     
        const pages = multiPage.context().pages();
        console.log('No.of tabs: ' + pages.length);
    

Procedure:

Repeat the first few steps as you did in the previous segment:

  • Under the “windows.test.ts” file, navigate to https://www.lambdatest.com/selenium-playground/window-popup-modal-demo.
  • Use the “promise.all” function. This function comes into the scenario when you need to perform simultaneous actions.
  • Next, you need to perform two tasks. The first one is “WaitForEvent,” which is a pop-up. Followed by a function called “click,” which contains an ID that says “#followboth.”
  • Also, an important step to follow here is to place “multiPage” instead of “newWindow” as you need to open multiple windows (in this case, 3 windows).
  • Use “const pages = multiPage.context().pages();” to know the number of pages that the test contains. Followed by “console.log (‘No. of tabs: ‘ + pages. length); to check the length and the number of available tabs.
  • Run the above test in the terminal; it directs us to the browser page. However, in the terminal, you can view only two tabs.
  • To fix the above issue, enter a new code into the test script. Type “pages.forEach(tab => {console.log(tab. url() and ); The above code helps in returning a single page at a time and also enables us to print all the open URLs.
  • Execute the test in the terminal. Again the terminal shows that the number of tabs available is 2. ( Twitter is not visible ).

Waiting for Load State in Playwright

It often happens that before all the pages get loaded completely, the browsers get closed. To fix this issue, use a function that says “waitForLoadState.” This function ensures that the browser waits until all the pages are loaded. However, use this function after the “followboth” function to obtain all the pages and wait for them to load successfully.

waitForLoadState Wait for Load State is a function used to wait until all the pages are loaded. Wait for Load State contains three states that are

  • dom-content loaded
  • Load
  • Networkidle

Now execute the test on the terminal, and eventually, you can view the main page along with two other browsers. Hence the terminal shows that the number of tabs available is 3.

const pages = multiPage.context().pages();
    console.log('No.of tabs: ' + pages.length);
 
    pages.forEach(tab => {
        console.log(tab.url());
    })

Interacting with multiple pages in Playwright

Let's continue with LambdaTest’s Selenium Playground (demo platform) to understand how to interact with multiple frames. In this case, there are three open pages. Consider using only the 1st and 2nd pages for interaction, as the other is a parent frame.

for (let index = 0; index < pages.length; index++) {
    const url = pages[index].url()
    if (url == "https://www.facebook.com/lambdatest/") {
        facebookPage = pages[index];
    }
}
const text = await facebookPage.textContent("//h1")
console.log(text);
  • Use the “For loop” function to know which page refers to Facebook.
  • Execute the test in the terminal and you will see all actions on the browser. Hence the test has run successfully.

Playwright automation is easy to understand; you only need basic knowledge of JavaScript and TypeScript. If you want to learn how to run tests with the help of Playwright automation, LambdaTest provides free Playwright 101 certification that will help you elevate your automation testing skills.

LambdaTest

How to scale Playwright tests with LambdaTest cloud?

So you have your Playwright tests ready with you, and you’ve executed them over your native browser as well. But what would you do if you were to run the same Playwright test over scores of hundreds of browser versions? That's where LambdaTest comes into play. With LambdaTest, you can take Playwright execution to the next level and run your tests on a cloud grid.

LambdaTest is a test orchestration and execution platform on the cloud with an automation testing grid of 3000+ browsers and operating systems to help you scale your Playwright test execution effortlessly. LambdaTest lets you:

  • Perform Playwright browser testing on 50+ browsers and browser versions such as Chrome, Firefox, Opera, Edge, etc.
  • Easily integrate with your CI/CD pipelines.
  • Debug Playwright tests using various logs, including network logs, command logs, and complete video recordings.
  • Run Playwright tests simultaneously on many configurations to reduce the time spent running tests.
  • Organize your test analytics by creating a custom dashboard and widgets.

LambdaTest’s automation testing cloud also supports Selenium, Cypress, Puppeteer, TestCafe, Taiko, and even app automation frameworks such as Appium, Espresso, XCUITest, etc.

To run the same test you have in your IDE on the LambdaTest cloud, you only need to make minor changes, i.e., declaring your LambdaTest username and LambdaTest access key in the code to authenticate access to LambdaTest cloud and declare test capabilities such as browsername, browser version, operating system and even advanced capabilities such as capturing command logs, network logs, etc. in a config.ts file.

You can access all those tests from the Playwright tutorial from this GitHub repo.

Want to know more about LambdaTest execution? Refer to the chapter that talks about cross-browser testing with LambdaTest.

Fun fact, you can trim your Playwright test execution times by multiple folds with LambdaTest’s parallel testing capabilities. You can also utilize HyperExecute, the quickest end-to-end test orchestration cloud by LambdaTest, to execute Playwright tests 70% faster than any testing cloud.

Conclusion

You have now learned about handling frames and windows in Playwright in detail. Concepts such as interaction with frames and windows, types of frames, and how these terms help simplify Playwright automation were explained in detail. In the next tutorial, you will learn about the automation of date pickers in Playwright.

The Playwright automation framework is fast, reliable, and easy compared to other frameworks and supports all major browsers. That's why its popularity propelled over time. To learn about Playwright testing, follow the LambdaTest YouTube channel.

Frequently Asked Questions (FAQs)

Why do we use iframes?

The most common use of an iframe is to load content from another site within the page. The child site can load its content and cookies, so sites may allow it where they don't allow direct hotlinking content. Using an iframe is the accepted way to embed a YouTube video or Google Maps content.

What is frame mapping?

Frame mapping uses computer algorithms to find terms that cluster together and are used exclusively by one or another of the stakeholders.

How does Selenium handle nested frames?

To work with different nested iframes, use the method switchTo() to switch the frames using Index, Name, or Id & Web Element. Moreover, you can switch to the immediate parent iframe using the method switchTo(). parentFrame(). You can switch to the main web page from the child iframe using the method switchTo().

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Did you find this page helpful?

Helpful

NotHelpful