CHAPTERS
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!
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.
Procedure:
There are two ways to view the test report.
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.â
Now letâs see how to interact with frames in the VS Code.
Procedure:
An alternative code for â?.â is the âifâ function. You can use the âifâ function to continue the test process.
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:
Run Automated Playwright Tests Online. Try LambdaTest Now!
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:
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.
Letâs use the LambdaTestâs Selenium Playground (A demo page) to show a live example of the test scenario.
Test Scenario:
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.â
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.
Letâs use LambdaTestâs Selenium Playground to show a live example of the test scenario.
Test Scenario:
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:
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
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());
})
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);
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.
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:
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.
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.
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.
Frame mapping uses computer algorithms to find terms that cluster together and are used exclusively by one or another of the stakeholders.
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!!
Did you find this page helpful?