In this article, we will see how we can handle multiple tabs on Playwright using java.
- In Playwright, we can handle multiple tabs or pages using page instances created using browser context.
- A Page refers to a single tab or a popup window within a browser context.
- Switching or bringing the page to the front is not required in Playwright like Selenium because each page behaves like a focused or active page when referred to using its page instance.
- Also, Pages created using context respect context-level emulation, like viewport sizes, custom network routes, or browser locale.
- For the demo, we will click on the By iVagus Services Pvt. Ltd. link in the copyright footer section of the programsbuzz website. After the click, a new tab will open with a different website, and we will get the title of the new and existing website using page instances.
package week4.day2;
import java.util.List;
import com.microsoft. Playwright.Browser;
import com.microsoft. Playwright.BrowserType;
import com.microsoft. Playwright.Page;
import com.microsoft. Playwright.Playwright;
public class Play {
public static void main(String[] args) {
Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
Page page = browser.newPage();
page.navigate("https://www.programsbuzz.com/");
page.waitForPopup(new Page.WaitForPopupOptions().setPredicate(p -> p.context().pages().size() == 2), () -> {
page.locator("a[href='https://www.ivagus.com']").click();
});
List<Page> pages = page.context().pages();
for (Page tabs : pages) {
tabs.waitForLoadState();
System.out.println(tabs.url());
}
Page pbPage = pages.get(0);
Page ivagusPage = pages.get(1);
System.out.println(pbPage.url());
System.out.println(ivagusPage.url());
page.close();
playwright.close();
}
}
- So here there are two pages one is programsbuzz, and the other one, when clicked, is the iVagus site.
- We first set waitForPopup and then setPredicate to 2, which means we are telling Playwright to wait for the popup, and the final result has two pages.
- Then we save the pages in a list, and then, using an advanced loop, we iterate the pages.
- This is one way of getting the total pages.
- We will use the list returned pages variable to operate on a particular page back and forth.
- Then we get the index of the two pages, programsbuzz and ivagus, and save them in a separate variable.
- This time we can move between these pages and operate on them.
- Log in to post comments