Execute Playwright Script on Chrome Browser

 

To execute a Playwright script in the Chrome browser using Java, you need to launch the browser in "Chrome" mode instead of the default "Chromium" (Playwright uses Chromium by default).

















Steps to Run Playwright in Chrome (Java):

  • Install Chrome on your system (Playwright will launch the installed Chrome browser).
  • Set the executable path of Chrome.
  • Use launchPersistentContext with Chrome executable path to launch Chrome.
  • Write and run your Playwright Java test.



Maven Dependency


<dependency>
  <groupId>com.microsoft.playwright</groupId>
  <artifactId>playwright</artifactId>
  <version>1.43.0</version> <!-- or latest -->
</dependency>





Java Code Example: Launch in Chrome


import com.microsoft.playwright.*;

import java.nio.file.Paths;

public class PlaywrightChromeExample {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {

      // Path to the installed Chrome browser executable
      String chromePath = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"; // Adjust this path

      BrowserType.LaunchOptions options = new BrowserType.LaunchOptions()
        .setExecutablePath(Paths.get(chromePath))
        .setHeadless(false); // Show the browser window

      Browser browser = playwright.chromium().launch(options);
      Page page = browser.newPage();
      page.navigate("https://example.com");

      System.out.println("Page title: " + page.title());

      browser.close();
    }
  }
}



No comments:

Post a Comment