Open a New Tab in Playwright

 

In Playwright Java, opening a new tab is done by creating a new Page from the existing BrowserContext. A tab in a browser corresponds to a Page object in Playwright. Here's how it works:



















Steps to Open a New Tab in Playwright Java:

  • Launch the browser.
  • Create a browser context using browser.newContext().
  • Open the first tab using context.newPage().
  • Open a second tab (new page) using the same context.newPage().
  • Navigate both tabs to different websites or perform other actions.

Example Website Used:

We'll use https://example.com for the first tab and https://playwright.dev for the second.



Java Code to Open New Tab in Playwright:


import com.microsoft.playwright.*;

public class OpenNewTabExample {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            // Step 1: Launch browser
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

            // Step 2: Create a new browser context
            BrowserContext context = browser.newContext();

            // Step 3: Open the first tab
            Page firstTab = context.newPage();
            firstTab.navigate("https://example.com");
            System.out.println("First tab title: " + firstTab.title());

            // Step 4: Open a new tab (second tab)
            Page secondTab = context.newPage();
            secondTab.navigate("https://playwright.dev");
            System.out.println("Second tab title: " + secondTab.title());

            // Wait so you can see the browser tabs before the program closes
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}



Explanation:

  • BrowserContext behaves like an incognito window — tabs (Pages) under the same context can share session data.

  • context.newPage() opens a new tab in the same browser window.

  • navigate(url) is used to open a website in that tab.

  • You can interact with both tabs using their respective Page objects.

No comments:

Post a Comment