Giter Site home page Giter Site logo

microsoft / playwright-java Goto Github PK

View Code? Open in Web Editor NEW
1.0K 39.0 186.0 5.86 MB

Java version of the Playwright testing and automation library

Home Page: https://playwright.dev/java/

License: Apache License 2.0

Java 98.37% HTML 1.31% CSS 0.01% Shell 0.31%
playwright java

playwright-java's Introduction

🎭 Playwright for Java

javadoc maven version Sonatype Nexus (Snapshots) Join Slack

Playwright is a Java library to automate Chromium, Firefox and WebKit with a single API. Playwright is built to enable cross-browser web automation that is ever-green, capable, reliable and fast.

Linux macOS Windows
Chromium 124.0.6367.18
WebKit 17.4
Firefox 124.0

Headless execution is supported for all the browsers on all platforms. Check out system requirements for details.

Usage

Playwright requires Java 8 or newer.

Add Maven dependency

Playwright is distributed as a set of Maven modules. The easiest way to use it is to add one dependency to your Maven pom.xml file as described below. If you're not familiar with Maven please refer to its documentation.

To run Playwright simply add following dependency to your Maven project:

<dependency>
  <groupId>com.microsoft.playwright</groupId>
  <artifactId>playwright</artifactId>
  <version>1.41.0</version>
</dependency>

To run Playwright using Gradle add following dependency to your build.gradle file:

dependencies {
  implementation group: 'com.microsoft.playwright', name: 'playwright', version: '1.41.0'
}

Is Playwright thread-safe?

No, Playwright is not thread safe, i.e. all its methods as well as methods on all objects created by it (such as BrowserContext, Browser, Page etc.) are expected to be called on the same thread where Playwright object was created or proper synchronization should be implemented to ensure only one thread calls Playwright methods at any given time. Having said that it's okay to create multiple Playwright instances each on its own thread.

Examples

You can find Maven project with the examples here.

Page screenshot

This code snippet navigates to Playwright homepage in Chromium, Firefox and WebKit, and saves 3 screenshots.

import com.microsoft.playwright.*;

import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

public class PageScreenshot {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      List<BrowserType> browserTypes = Arrays.asList(
        playwright.chromium(),
        playwright.webkit(),
        playwright.firefox()
      );
      for (BrowserType browserType : browserTypes) {
        try (Browser browser = browserType.launch()) {
          BrowserContext context = browser.newContext();
          Page page = context.newPage();
          page.navigate("https://playwright.dev/");
          page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot-" + browserType.name() + ".png")));
        }
      }
    }
  }
}

Mobile and geolocation

This snippet emulates Mobile Chromium on a device at a given geolocation, navigates to openstreetmap.org, performs action and takes a screenshot.

import com.microsoft.playwright.options.*;
import com.microsoft.playwright.*;

import java.nio.file.Paths;

import static java.util.Arrays.asList;

public class MobileAndGeolocation {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium().launch();
      BrowserContext context = browser.newContext(new Browser.NewContextOptions()
        .setUserAgent("Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36")
        .setViewportSize(411, 731)
        .setDeviceScaleFactor(2.625)
        .setIsMobile(true)
        .setHasTouch(true)
        .setLocale("en-US")
        .setGeolocation(41.889938, 12.492507)
        .setPermissions(asList("geolocation")));
      Page page = context.newPage();
      page.navigate("https://www.openstreetmap.org/");
      page.click("a[data-original-title=\"Show My Location\"]");
      page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("colosseum-pixel2.png")));
    }
  }
}

Evaluate JavaScript in browser

This code snippet navigates to example.com in Firefox, and executes a script in the page context.

import com.microsoft.playwright.*;

public class EvaluateInBrowserContext {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.firefox().launch();
      BrowserContext context = browser.newContext();
      Page page = context.newPage();
      page.navigate("https://www.example.com/");
      Object dimensions = page.evaluate("() => {\n" +
        "  return {\n" +
        "      width: document.documentElement.clientWidth,\n" +
        "      height: document.documentElement.clientHeight,\n" +
        "      deviceScaleFactor: window.devicePixelRatio\n" +
        "  }\n" +
        "}");
      System.out.println(dimensions);
    }
  }
}

Intercept network requests

This code snippet sets up request routing for a WebKit page to log all network requests.

import com.microsoft.playwright.*;

public class InterceptNetworkRequests {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.webkit().launch();
      BrowserContext context = browser.newContext();
      Page page = context.newPage();
      page.route("**", route -> {
        System.out.println(route.request().url());
        route.resume();
      });
      page.navigate("http://todomvc.com");
    }
  }
}

Documentation

Check out our official documentation site.

You can also browse javadoc online.

Contributing

Follow the instructions to build the project from source and install the driver.

Is Playwright for Java ready?

Yes, Playwright for Java is ready. v1.10.0 is the first stable release. Going forward we will adhere to semantic versioning of the API.

playwright-java's People

Contributors

ariamoradi avatar aslushnikov avatar brunoborges avatar codeboyzhou avatar dependabot[bot] avatar ephung01 avatar gabriel20200 avatar helpermethod avatar htr3n avatar jayapraveen avatar jfgreffier avatar jlleitschuh avatar jnizet avatar khmarbaise avatar kumaraditya303 avatar leonard84 avatar maxandersen avatar meir017 avatar mxschmitt avatar otterley avatar oweis avatar pranesh517 avatar railwayursin avatar raphiz avatar sebastienrichert avatar uchagani avatar vania-pooh avatar vlad-velichko avatar yury-s avatar zibdie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

playwright-java's Issues

[Question] How to await/resolve `Deferred<Void> page.waitForTimeout()` method?

I am trying to log in to a web page and take a certain set of actions using Playwright. Once the LOGIN button is click the browser takes me to the dashboard. And I need to certain actions on the reporting page. So my code goes like this:

// Sign in
Browser = playwright.chromium().launch();

final Page page = context.newPage();

// Navigate to the SIGNIN page
page.navigate("https://www.example.com/signin");

// Fill in the username
page.fill("#username", "foo");

// Fill in the password
page.fill("#password", "password");


// Click the LOGIN button
page.click("button[type='submit']");

// Once the LOGIN button is clicked you will be taken to the Dashboard page
// and you can navigate to the reporting page from here.
// Make sure the browser navigates to the dashboard by waiting for 10 seconds
page.waitForTimeout(10000);

// Navigate to the reporting page.
page.navigate("https://www.example.com/reporting");

page.fill("#date1", "2020-11-20");
page.fill("#date2", "2021-01-08");

However, when I do this, the page.waitForTimeout(10000) does not wait for 10 seconds. and the code continues to run without waiting. How can I make it actually wait?

[Question] Disabled cache resources?

Hi there,

We are facing a weird behaviour with Playwright Java. We are testing load speed of different websites and we have seen that chromium is not caching resources. With the same chromium version and config in nodejs we see memory and disk cache sources for resources like js, images, ... in network tab (javascript console), but it doesn't happen when we execute in Java

We are a bit lost because it seems all ok, could you please guide us?

Thanks a lot

Dockerfile for playwright-java

Thanks again for creating this awesome project. 👏

Do you guys happen to have a Dockerfile for playwright-java ? or any tips on how I can create one ?

[BUG] no instruction for fixing missing vcruntime140_1.dll in firefox

Copied from email from @ephung01:

There is no instruction print out for missing installation of VS distribution info as the code link you provide. I test this on a different laptop and here is the full log.

[INFO] Scanning for projects...
[INFO] Inspecting build with total of 4 modules...
[INFO] Installing Nexus Staging features:
[INFO] ... total of 4 executions of maven-deploy-plugin replaced with nexus-staging-maven-plugin
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO]
[INFO] Playwright Parent Project [pom]
[INFO] Playwright - Driver [jar]
[INFO] Playwright - Drivers For All Platforms [jar]
[INFO] Playwright - Main Library [jar]
[INFO]
[INFO] ----------------< com.microsoft.playwright:parent-pom >-----------------
[INFO] Building Playwright Parent Project 0.180.0-SNAPSHOT [1/4]
[INFO] --------------------------------[ pom ]---------------------------------
[INFO]
[INFO] ------------------< com.microsoft.playwright:driver >-------------------
[INFO] Building Playwright - Driver 0.180.0-SNAPSHOT [2/4]
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ driver ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ driver ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ driver ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Users\ephun\Development\playwright-java\driver\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ driver ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-surefire-plugin:3.0.0-M5:test (default-test) @ driver ---
[INFO] No tests to run.
[INFO]
[INFO] ---------------< com.microsoft.playwright:driver-bundle >---------------
[INFO] Building Playwright - Drivers For All Platforms 0.180.0-SNAPSHOT [3/4]
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ driver-bundle ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 19 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ driver-bundle ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ driver-bundle ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Users\ephun\Development\playwright-java\driver-bundle\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ driver-bundle ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:3.0.0-M5:test (default-test) @ driver-bundle ---
[INFO]
[INFO] ----------------< com.microsoft.playwright:playwright >-----------------
[INFO] Building Playwright - Main Library 0.180.0-SNAPSHOT [4/4]
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ playwright ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Users\ephun\Development\playwright-java\playwright\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ playwright ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 79 source files to C:\Users\ephun\Development\playwright-java\playwright\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ playwright ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 135 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ playwright ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:3.0.0-M5:test (default-test) @ playwright ---
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.microsoft.playwright.TestElementHandleSelectText
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 2.727 s <<< FAILURE! - in
com.microsoft.playwright.TestElementHandleSelectText
[ERROR] com.microsoft.playwright.TestElementHandleSelectText Time elapsed: 2.727 s <<< ERROR!
com.microsoft.playwright.PlaywrightException:
Error: Host system is missing dependencies!

Full list of missing libraries:
vcruntime140_1.dll

Note: use DEBUG=pw:api environment variable and rerun to capture Playwright logs.
Caused by: com.microsoft.playwright.impl.ServerException:
Error: Host system is missing dependencies!

Full list of missing libraries:
vcruntime140_1.dll

Note: use DEBUG=pw:api environment variable and rerun to capture Playwright logs.

[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR] TestElementHandleSelectText>TestBase.launchBrowser:85->TestBase.launchBrowser:80 Playwright
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary for Playwright Parent Project 0.180.0-SNAPSHOT:
[INFO]
[INFO] Playwright Parent Project .......................... SUCCESS [ 0.016 s]
[INFO] Playwright - Driver ................................ SUCCESS [ 0.717 s]
[INFO] Playwright - Drivers For All Platforms ............. SUCCESS [ 0.090 s]
[INFO] Playwright - Main Library .......................... FAILURE [ 5.587 s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 7.126 s
[INFO] Finished at: 2021-01-09T16:04:59-05:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:3.0.0-M5:test (default-test) on project playwr ight
: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\ephun\Development\playwright-java\playwright\target\surefire-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR] mvn -rf :playwright

ephun@DESKTOP-OVJ124Q MINGW64 ~/Development/playwright-java (testElementSelectText)

[Question] StackOverflowError: com.google.gson.internal loop error

Hi, im testing the playwright-java maven plugin, the version 0.180.0, with JDK 1.8 and maven project in java 1.8.
I have a loop error trying the example test PageScreenshot

This is the loop error:

Exception in thread "main" java.lang.StackOverflowError
	at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:378)
	at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:383)

       // + 750 times loop code

	at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:358)
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:158)
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
	at com.google.gson.Gson.getAdapter(Gson.java:423)
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
	at com.google.gson.Gson.getAdapter(Gson.java:423)
	// + 250 times loop code
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
	at com.google.gson.Gson.getAdapter(Gson.java:423)
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)

How can I solve this?
Thanks everyone for your help

[Question] NoSuchFileException in jar file

I didn't find any decision yet for this problem. I cannot execute jar file with my spring-boot service using playwright.

java.lang.IllegalStateException: Failed to execute CommandLineRunner
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:782)
        at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:763)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:318)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1213)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1202)
        at ru.cnd.Application.main(Application.java:14)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:51)
        at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:52)
Caused by: java.lang.RuntimeException: Failed to create driver
        at com.microsoft.playwright.impl.Driver.ensureDriverInstalled(Driver.java:46)
        at com.microsoft.playwright.impl.PlaywrightImpl.create(PlaywrightImpl.java:40)
        at com.microsoft.playwright.Playwright.create(Playwright.java:50)
        at ru.cnd.config.BrowserInitialize.launchBrowser(BrowserInitialize.java:12)
        at ru.cnd.config.ServiceInitialize.lambda$configAuthentication$0(ServiceInitialize.java:35)
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:779)
        ... 13 common frames omitted
Caused by: java.lang.reflect.InvocationTargetException: null
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
        at com.microsoft.playwright.impl.Driver.createDriver(Driver.java:65)
        at com.microsoft.playwright.impl.Driver.ensureDriverInstalled(Driver.java:44)
        ... 18 common frames omitted
Caused by: java.nio.file.NoSuchFileException: /BOOT-INF/lib/driver-bundle-0.180.0.jar!/driver/linux
        at jdk.zipfs/jdk.nio.zipfs.ZipPath.getAttributes(ZipPath.java:742)

I found that getResource() causes this exception, but I'm not sure that it is my case.
This method in DriverJar.class has such code

private void extractDriverToTempDir() throws URISyntaxException, IOException { ClassLoader classloader = Thread.currentThread().getContextClassLoader(); URI uri = classloader.getResource("driver/" + platformDir()).toURI();

Please, how can I run my jar file correctly or find the reason of such exception?

[BUG] Can't work with some selectors

undefined:1
{"id":5,"guid":"Frame@3f7bb17e06603ea8d8186b3190c0e61c","method":"click","params":{"selector":"xpath \u003d //*[text()\u003d\u0027�09B8\u0027]"}}
^

SyntaxError: Unexpected token � in JSON at position 130
at JSON.parse ()
at Transport.onmessage (/snapshot/playwright-cli/lib/driver.js:48:75)
at Immediate. (/snapshot/playwright-cli/node_modules/playwright/lib/protocol/transport.js:70:26)
at processImmediate (internal/timers.js:456:21)

testCode
@test
public void test () throws Exception {
Playwright playwright = Playwright.create();
List browserTypes = Arrays.asList(
playwright.chromium(),
playwright.webkit()
);
for (BrowserType browserType : browserTypes) {
BrowserType.LaunchOptions options = new BrowserType.LaunchOptions();
options.headless = false;
Browser browser = browserType.launch(options);
BrowserContext context = browser.newContext(
new Browser.NewContextOptions().withViewport(800, 600));
Page page = context.newPage();
page.navigate("http://ya.ru");
page.click("xpath = //*[text()='Найти']");
page.screenshot(new Page.ScreenshotOptions().withPath(Paths.get("screenshot-" + browserType.name() + ".png")));
browser.close();
}
playwright.close();
}

BrowserType.LaunchOption set option 'withEnv' type mismatch

When use BrowserType.LaunchOptions to set environment, the function definition syntax of 'withEnv' has parameter as string, but when compile it's fail on type check asking parameter as an Array of string

playWright = Playwright.create();
BrowserType browserType = playWright.chromium();
BrowserType.LaunchOptions options = new BrowserType.LaunchOptions();
options.withEnv("DEBUG=pw:protocol");

parameter define as string
image

compilation error: expect an array
image

[Bug] Improve ignoreDefaultArgs option

I came here while reviewing this property in the .NET version. I think we can make some improvements.
public Boolean ignoreDefaultArgs; could be an object.
We could have withIgnoreDefaultArgs with overloads.

public LaunchOptions withIgnoreDefaultArgs(List<String> ignoreDefaultArgs) {
    this.ignoreDefaultArgs = ignoreDefaultArgs;
    return this;
}
public LaunchOptions withIgnoreDefaultArgs(Boolean ignoreDefaultArgs) {
    this.ignoreDefaultArgs = ignoreDefaultArgs;
    return this;
}

I also found that this option is a string in LaunchPersistentContextOptions is that ok?

请问playwright-java是否支持centos6?

求救,playwright-java是否支持centos6,安装依赖包崩溃中。。。
利用Jenkins在centos6.9上跑playwright-java,提示缺少包
Missing libraries are: libatk-bridge-2.0.so.0 libxkbcommon.so.0 libgbm.so.1 libgtk-3.so.0 libgdk-3.so.0 libatspi.so.0 libxshmfence.so.1
image

[BUG] TestWaitForFunction is failing

[ERROR] TestWaitForFunction.shouldAvoidSideEffectsAfterTimeout:82 did not throw
[ERROR] TestWaitForFunction.shouldFailWithPredicateThrowingOnFirstCall:106 did not throw
[ERROR] TestWaitForFunction.shouldFailWithPredicateThrowingSometimes:121 did not throw
[ERROR] TestWaitForFunction.shouldFailWithReferenceErrorOnWrongPage:131 did not throw
[ERROR] TestWaitForFunction.shouldNotBeCalledAfterFinishingSuccessfully:260 expected: <[waitForFunction1, waitForFunction2, waitForFunction3]> but was: <[]>
[ERROR] TestWaitForFunction.shouldNotBeCalledAfterFinishingUnsuccessfully:277 did not throw
[ERROR] TestWaitForFunction.shouldWorkWithMultilineBody:228 expected: but was:
[ERROR] Errors:
[ERROR] TestWaitForFunction.shouldPollOnInterval:68 NullPointer

[Feature] Connect to running browser missing

BrowserType.connect is missing from the implementation.

The api defines https://github.com/microsoft/playwright/blob/master/docs/api.md#browsertypeconnectparams but seems to be missing from the java implementation.

Example code (node.js)

const pw = require('playwright');

(async () => {

    const browser = await pw.chromium.connect({
        wsEndpoint: 'ws://localhost:3000/playwright',
    });

    const context = await browser.newContext();
    const page = await context.newPage();
    await page.goto('http://whatsmyuseragent.org/');
    await page.screenshot({ path: `example-connect.png` });
    await browser.close();

})();

Dockerfile is outdated

Hello,

Dockerfile.focal looks to be outdated and references script that is no more existing :
./scripts/download_driver.sh
As a consequence the image can't be build .

Regards.
Michael

[Question] Failed to launch chromium because executable doesn't exist

Hi, I have an issue launching the Chromium browser, on Ubuntu 20 LTS. The error only occurs one one of three Ubuntu 20 servers, so hopefully it is a configuration issue, but the error message seems like it's maybe an overhang from the node version.

This is being run from within a Tomcat 9 Java servlet application. The Playwright version is v1.9.1-alpha-0.

My code is

private static void generatePdfPlaywright(File htmlSourceFile, File pdfToGenerate) {
    try (Playwright playwright = Playwright.create();
         Browser browser = playwright.chromium().launch();
         BrowserContext browserContext = browser.newContext(new Browser.NewContextOptions().setViewportSize(1280, 800));
         Page page = browserContext.newPage()) {
        page.navigate("file://" + htmlSourceFile.getAbsolutePath());
        Page.PdfOptions pdfOptions = new Page.PdfOptions().setFormat("A4").setPath(pdfToGenerate.toPath());
        page.pdf(pdfOptions);
    }
}

and the stack trace is

 -  - com.microsoft.playwright.impl.DriverException: Error {
  message='Failed to launch chromium because executable doesn't exist at /.cache/ms-playwright/chromium-854489/chrome-linux/chrome
Try re-installing playwright with "npm install playwright"
  name='Error
  stack='Error: Failed to launch chromium because executable doesn't exist at /.cache/ms-playwright/chromium-854489/chrome-linux/chrome
Try re-installing playwright with "npm install playwright"
    at Chromium._launchProcess (/tmp/playwright-java-5158158360901142005/package/lib/server/browserType.js:173:19)
    at async Chromium._innerLaunch (/tmp/playwright-java-5158158360901142005/package/lib/server/browserType.js:110:62)
    at async ProgressController.run (/tmp/playwright-java-5158158360901142005/package/lib/server/progress.js:79:28)
    at async Chromium.launch (/tmp/playwright-java-5158158360901142005/package/lib/server/browserType.js:78:25)
    at async BrowserTypeDispatcher.launch (/tmp/playwright-java-5158158360901142005/package/lib/dispatchers/browserTypeDispatcher.js:30:25)
    at async DispatcherConnection.dispatch (/tmp/playwright-java-5158158360901142005/package/lib/dispatchers/dispatcher.js:178:28)
}
 - Stack trace:
   com.microsoft.playwright.impl.Connection.dispatch(Connection.java:209)
   com.microsoft.playwright.impl.Connection.processOneMessage(Connection.java:189)
   com.microsoft.playwright.impl.ChannelOwner.runUntil(ChannelOwner.java:86)
   com.microsoft.playwright.impl.Connection.sendMessage(Connection.java:96)
   com.microsoft.playwright.impl.ChannelOwner.sendMessage(ChannelOwner.java:79)
   com.microsoft.playwright.impl.BrowserTypeImpl.launchImpl(BrowserTypeImpl.java:49)
   com.microsoft.playwright.impl.BrowserTypeImpl.lambda$launch$0(BrowserTypeImpl.java:41)
   com.microsoft.playwright.impl.LoggingSupport.withLogging(LoggingSupport.java:47)
   com.microsoft.playwright.impl.BrowserTypeImpl.launch(BrowserTypeImpl.java:41)
   com.microsoft.playwright.impl.BrowserTypeImpl.launch(BrowserTypeImpl.java:34)
   com.microsoft.playwright.BrowserType.launch(BrowserType.java:582)
   com.gtwm.pb.background.SubscriptionSender.generatePdfPlaywright(SubscriptionSender.java:161)
   com.gtwm.pb.background.SubscriptionSender.sendReportSubscriptions(SubscriptionSender.java:97)
   com.gtwm.pb.background.SubscriptionSender.run(SubscriptionSender.java:55)
   com.gtwm.pb.servlets.ServletDataMethods.sendReportSubscription(ServletDataMethods.java:566)
   com.gtwm.pb.servlets.AppController.carryOutAppActions(AppController.java:617)
   com.gtwm.pb.servlets.AppController.handleRequest(AppController.java:878)
   org.apache.velocity.tools.view.VelocityViewServlet.doRequest(VelocityViewServlet.java:236)
 - Stack trace:
   com.microsoft.playwright.impl.WaitableResult.get(WaitableResult.java:54)
   com.microsoft.playwright.impl.ChannelOwner.runUntil(ChannelOwner.java:88)
   com.microsoft.playwright.impl.Connection.sendMessage(Connection.java:96)
   com.microsoft.playwright.impl.ChannelOwner.sendMessage(ChannelOwner.java:79)
   com.microsoft.playwright.impl.BrowserTypeImpl.launchImpl(BrowserTypeImpl.java:49)
   com.microsoft.playwright.impl.BrowserTypeImpl.lambda$launch$0(BrowserTypeImpl.java:41)
   com.microsoft.playwright.impl.LoggingSupport.withLogging(LoggingSupport.java:47)
   com.microsoft.playwright.impl.BrowserTypeImpl.launch(BrowserTypeImpl.java:41)
   com.microsoft.playwright.impl.BrowserTypeImpl.launch(BrowserTypeImpl.java:34)
   com.microsoft.playwright.BrowserType.launch(BrowserType.java:582)
   com.gtwm.pb.background.SubscriptionSender.generatePdfPlaywright(SubscriptionSender.java:161)

Can you think of any possible causes?

[Feature] Consider implementing AutoCloseable

Playwright, BrowserContext, Browser and Page all have a close() method. And I guess that not calling them when we're done with those objects has a negative impact on resources.
To make that clearer, and more importantly, to be able to use standard Java constructs simplifying the proper handling of resources that must be closed, consider extening AutoCloseable in those 4 interfaces. It would allow, in Java to do:

try (
    Playwright playwright = Playwright.create();
    Browser browser = playwright.chromium();
    BrowserContext browserContext = browser.newContext();
    Page page = browserContext.newPage()) {
  
}

and all those resources would be properly closed, even in case an exception is thrown, and without having to explicitly call close().

Other JVM languages like Kotlin have similar constructs:

Playwright.create().use { playwright ->
    playwright.chromium().use { browser ->
        // ...
    }
}

But those constructs can't be used if those interfaces don't implement AutoCloseable. And code inspection tools also won't warn about missing close() calls.

Error doesn't shows when playwright can't find selector

Expected result: User see exception If he try to find elementHandle which doesn't exist when timeout is done.

@test
public void test () throws Exception {
Playwright playwright = Playwright.create();
List browserTypes = Arrays.asList(
playwright.chromium(),
playwright.webkit()
);
for (BrowserType browserType : browserTypes) {
BrowserType.LaunchOptions options = new BrowserType.LaunchOptions();
options.headless = false;
Browser browser = browserType.launch(options);
BrowserContext context = browser.newContext(
new Browser.NewContextOptions().withViewport(800, 600));
Page page = context.newPage();
page.navigate("http://ya.ru");
page.waitForSelector(""text = ура123123123"", new Page.WaitForSelectorOptions()
.withState(Page.WaitForSelectorOptions.State.ATTACHED));
page.screenshot(new Page.ScreenshotOptions().withPath(Paths.get("screenshot-" + browserType.name() + ".png")));
browser.close();
}
playwright.close();
}

Playwright and Browser not implementing AutoCloseable

I get an error on
(Playwright playwright = Playwright.create())
I checked the Playwright interface code in the libraries of my project and found out that it doesn't implement AutoCloseable (same thing for Browser interface) but the code here on github has them both implementing AutoCloseable
here is my code snippet :

 try (Playwright playwright = Playwright.create()) {
        BrowserType firefox = playwright.firefox()
        Browser browser = firefox.launch();
        Page page = browser.newPage();
        page.navigate("https://example.com");
       browser.close();}

[BUG] SimpleDateFormat in LoggingSupport is not thread-safe

the timestampFormat used in LoggingSupport is not treated well, cuz it is not thread-safe

  private static final SimpleDateFormat timestampFormat;

consider using fresh instance per call or adding locks or using java8-thread-safe time formatter?
In my opinion, let's use java8 time formatter :)

Failed to process descriptor

Fabulous project. Thanks for creating it!

My playwright java program works just fine but I always get the following warning:
Failed to process descriptor at C:\Users\SKANGA\AppData\Local\Temp\playwright-java-6634219733458767107

What does this mean and how do I prevent it?
Thanks

[Question] Custom Element Implementation

What is the best practice to implement a custom element. For example, we have a combobox that isn't a normal html select option. There are certain workarounds for how to select an option.

I was thinking about implementing the ElementHandle interface and passing in the page and the locator for the root element. Something like this:

public class CustomComboBox implements ElementHandle {
  private ElementHandle elementHandle;

  public CustomComboBox(Page page, String selector) {
    this.elementHandle = page.querySelector(selector);
  }
}

For all of the methods i would just pass on the method call to the elementHandle. And for the selectOption methods I would implement the custom logic needed to select an option in this custom combobox.

Is there a better way to do this?

[BUG] Can't seem to get viewport = null and lauch args --start-maximized to work

Based on the docs and node.js version viewport null should maximize viewport and launch args "--start-maximized" to launch browser (chromium in my case) maximized.

Did I miss something?

Test code below:

package org.example;

import com.microsoft.playwright.*;

import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;


public class PageScreenshot {

  public static void main(String[] args) throws Exception {
    try (Playwright playwright = Playwright.create()) {
          
      BrowserType browserType = playwright.chromium();
     
      Browser.NewContextOptions options = new Browser.NewContextOptions();
      options.viewport = null;

      BrowserType.LaunchOptions launchOptions = new BrowserType.LaunchOptions().withArgs(Arrays.asList(new String[]{"--start-maximized"}));
      launchOptions.withHeadless(false);

      try (Browser browser = browserType.launch(launchOptions);
            BrowserContext context = browser.newContext(options);
            Page page = context.newPage()) {
        page.navigate("http://whatsmyuseragent.org/");
        page.screenshot(new Page.ScreenshotOptions().withPath(Paths.get("screenshot-" + browserType.name() + ".png")));
    
        System.out.print("Press enter to quit . . . ");
        System.in.read();
      }
    }
  }
}

This works as intented on node.js version

const { chromium } = require('playwright');

async function test() {
    const browser = await chromium.launch({
        args: ['--start-maximized'],
        headless : false, slowMo : 50});
    const context = await browser.newContext({viewport : null});
    const loginPage = await context.newPage();
    await loginPage.goto('http://todomvc.com'); 
}

test();

Also the "mvn compile exec:java -Dexec.mainClass=org.example.PageScreenshot" in readme to run example did not work.
Fixed that with:

<plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>3.0.0</version>
            <configuration>
                <mainClass>org.example.PageScreenshot</mainClass>
            </configuration>
        </plugin>

Then mvn compile exec:java to execute

[Question] NETWORKIDLE event fired eventhough the url is not loaded completely.

This works perfectly in pupeeteer . I am trying to convert the node.js code to java , so using playwright java code to automate my test case.

Have tried all below options to stop closing the browser before taking screenshot. But without fully loading the specified url it takes screenshot and closes the browser.

NavigateOptions navigateOptions = new NavigateOptions();
navigateOptions.withWaitUntil(LoadState.NETWORKIDLE);
page.waitForResponse(url);
WaitForSelectorOptions waitForSelectorOptions = new WaitForSelectorOptions();
waitForSelectorOptions.withState(State.VISIBLE);
page.waitForSelector("view", waitForSelectorOptions);
page.waitForSelector("react-grid-layout", waitForSelectorOptions);
page.waitForSelector("view", waitForSelectorOptions);
page.waitForSelector("dashboard-content", waitForSelectorOptions);
page.waitForSelector("react-grid-item", waitForSelectorOptions);
//Even tried to fulfil the response by 200

page.route(grafanaUrl, r -> {
				r.fulfill(new FulfillResponse().withStatus(200));
			});
page.navigate(grafanaUrl,navigateOptions);
			page.screenshot(new Page.ScreenshotOptions().withPath(Paths.get("screenshot-" + browserType.name() + ".png")));

Pupeeteer equivalent code that works - await page.goto(rUrl, { waitUntil: 'networkidle0' });
Any help could be appreciated.

[test] Test failed: com.microsoft.playwright.TestBrowserContextProxy.shouldExcludePatterns

Test failed on windows: Chromium/Webkit/Firefox

[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.microsoft.playwright.TestBrowserContextProxy
[ERROR] WARNING: An illegal reflective access operation has occurred
[ERROR] WARNING: Illegal reflective access by com.google.gson.internal.reflect.UnsafeReflectionAccessor (file:/C:/Users/ephun/.m2/repository/com/google/code/gson/gson/2.8.6/gson-2.8.6.jar) to field java.io.DataInputStream.bytearr
[ERROR] WARNING: Please consider reporting this to the maintainers of com.google.gson.internal.reflect.UnsafeReflectionAccessor
[ERROR] WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
[ERROR] WARNING: All illegal access operations will be denied in a future release
[ERROR] Tests run: 8, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 10.94 s <<< FAILURE! - in com.microsoft.playwright.TestBrowserContextProxy
[ERROR] com.microsoft.playwright.TestBrowserContextProxy.shouldExcludePatterns Time elapsed: 0.409 s <<< FAILURE!
org.opentest4j.AssertionFailedError: did not throw
at com.microsoft.playwright.TestBrowserContextProxy.shouldExcludePatterns(TestBrowserContextProxy.java:180)

[BUG] Blank Password in proxy results in no credential sent for authentication

There are 3rd party proxy services like Crawlera, that require its users to use a blank password (empty string), for the its service. Please see the the Proxy API for reference.

I am starting to look into the cause of this. It may be due to some default GSON config that treats blank strings as nulls when converting to JSON.

Here is a sample test (adapted from TestBrowserContextProxy) that demonstrates the failure:

  @Test
  void shouldAuthenticateWithBlankPassword() {
    server.setRoute("/target.html", exchange -> {
      List<String> auth = exchange.getRequestHeaders().get("proxy-authorization");
      if (auth == null) {
        exchange.getResponseHeaders().add("Proxy-Authenticate", "Basic realm='Access to internal site'");
        exchange.sendResponseHeaders(407, 0);
        exchange.getResponseBody().close();
        return;
      }
      exchange.sendResponseHeaders(200, 0);
      try (OutputStreamWriter writer = new OutputStreamWriter(exchange.getResponseBody())) {
        writer.write("<html><title>" + auth.get(0) + "</title></html>");
      }
    });
    BrowserContext context = browser.newContext(new Browser.NewContextOptions().setProxy()
      .withServer("localhost:" + server.PORT)
      .withUsername("user")
      .withPassword("").done());
    Page page = context.newPage();
    page.navigate("http://non-existent.com/target.html");
    assertEquals("Basic " + Base64.getEncoder().encodeToString("user:".getBytes()), page.title());
    context.close();
  }

The assertion fails because the page.title() evaluates to "" (empty string)

[Question] Is it any plans for async interfaces?

Currently when video record is enabled closing context taking additional 15-20 second, so im curious will async operation be available in neares future or maybe there is a way to dissmiss video recording (like when test passed there is no need of video)

[Question] Is HAR recording possible

Sorry if this is a silly question, but I just learned of this library and was wondering, whether or not Playwright-Java can do HAR capturing.

A quick search seemed to indicate that on node.js this seems possible... Am I correct?

Thanks in advance!

[Bug] Firefox setFirefoxUserPrefs is broken

It seems as though setFirefoxUserPrefs currently does not work as intended. Given the following code:

try (final Playwright playwright = Playwright.create();
             final Browser browser = playwright.firefox().launch(new LaunchOptions()
                     .setHeadless(false)
                     .setFirefoxUserPrefs(Map.of(
                             "privacy.resistFingerprinting", true,
                             "privacy.resistFingerprinting.randomDataOnCanvasExtract", false)))) {
                                 final BrowserContext context = browser.newContext();
                                 final Response response = context.newPage().navigate("https://browserleaks.com/canvas");
                         }
}

There is a runtime error:

Caused by: com.microsoft.playwright.PlaywrightException: Unexpected map type: java.util.Map<java.lang.String, java.lang.Object>
	at com.microsoft.playwright.impl.Serialization$StringMapSerializer.serialize(Serialization.java:281) ~[classes/:na]
	at com.microsoft.playwright.impl.Serialization$StringMapSerializer.serialize(Serialization.java:1) ~[classes/:na]
	at com.google.gson.internal.bind.TreeTypeAdapter.write(TreeTypeAdapter.java:81) ~[gson-2.8.6.jar:na]
	at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:69) ~[gson-2.8.6.jar:na]
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:127) ~[gson-2.8.6.jar:na]
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:245) ~[gson-2.8.6.jar:na]
	at com.google.gson.Gson.toJson(Gson.java:704) ~[gson-2.8.6.jar:na]
	at com.google.gson.Gson.toJsonTree(Gson.java:597) ~[gson-2.8.6.jar:na]
	at com.google.gson.Gson.toJsonTree(Gson.java:576) ~[gson-2.8.6.jar:na]
	at com.microsoft.playwright.impl.BrowserTypeImpl.launchImpl(BrowserTypeImpl.java:48) ~[classes/:na]
	at com.microsoft.playwright.impl.BrowserTypeImpl.lambda$0(BrowserTypeImpl.java:41) ~[classes/:na]
	at com.microsoft.playwright.impl.LoggingSupport.withLogging(LoggingSupport.java:47) ~[classes/:na]
	at com.microsoft.playwright.impl.BrowserTypeImpl.launch(BrowserTypeImpl.java:41) ~[classes/:na]
	at com.microsoft.playwright.impl.BrowserTypeImpl.launch(BrowserTypeImpl.java:1) ~[classes/:na]

When manually patching the latest SNAPSHOT version to fix above runtime exception, the provided user preferences do not seem to be applied to Firefox (when checking about:config in the headful window).

[Question] - how to use for page navigates to a new URL or reloads?

I want to using page.waitForNavigation in Java for page navigates to a new URL or reloads, liked in JavaScript and Python:

  • js:
const [response] = await Promise.all([
  page.waitForNavigation(), // The promise resolves after navigation has finished
  page.click('a.delayed-navigation'), // Clicking the link will indirectly cause a navigation
]);
  • python:
with page.expect_navigation():
    page.click("a.delayed-navigation") # Clicking the link will indirectly cause a navigation
# Context manager waited for the navigation to happen.

How to write above code in Java, can you give me an example?

[BUG] Can't run in Springboot application

When I use spring-boot-maven-plugin to build a jar and use java -jar demo.jar, it dosen't run and throws exception.

java.nio.file.NoSuchFileException: /BOOT-INF/lib/driver-bundle-0.180.0.jar!/driver/win32_x64
at com.sun.nio.zipfs.ZipPath.getAttributes(ZipPath.java:666)
at com.sun.nio.zipfs.ZipFileSystemProvider.readAttributes(ZipFileSystemProvider.java:294)
at java.nio.file.Files.readAttributes(Unknown Source)
at java.nio.file.FileTreeWalker.getAttributes(Unknown Source)
at java.nio.file.FileTreeWalker.visit(Unknown Source)
at java.nio.file.FileTreeWalker.walk(Unknown Source)
at java.nio.file.FileTreeIterator.(Unknown Source)
at java.nio.file.Files.walk(Unknown Source)
at java.nio.file.Files.walk(Unknown Source)
at com.microsoft.playwright.impl.DriverJar.extractDriverToTempDir(DriverJar.java:58)
at com.microsoft.playwright.impl.DriverJar.(DriverJar.java:18)
... 17 more

[BUG] new page in context open when execute javascript from page object

when execute the Javascript from the page.evaluate, there is a new page created with url ":". The page close status is false, but when try to close, the process will get stuck- this also affect when tear down which call browser close. I am using v 0.17.2 and Microsoft Chromium Edge 86.

image

[Question] target release date

Not an issue but just a question.

Do you have a target release date for version 1?
I want to use this for my next project. I'm more comfortable with java than JS/TS.

[BUG] 'PlaywrightException: Error: Navigation failed because page crashed!' on Linux

OS: Ubuntu 20.04 LTS on WSL, Debian GNU/Linux 10 on WSL after adding required dependencies
Playwright Java: 0.180.0, 1.9.0-alpha-0
This issue is not observed on Windows 10.

        final Playwright playwright = Playwright.create();
        final List<BrowserType> browserTypes = Arrays.asList(
                playwright.chromium()
        );

        for (final BrowserType browserType : browserTypes) {
            final Browser browser = browserType.launch();
            final BrowserContext context = browser.newContext();
            final Page page = context.newPage();

            page.navigate("http://playwright.dev");
        }
        playwright.close();

Error log 1.9.0-alpha-0:

[ERROR] 2021-03-07T08:35:31.695Z pw:api navigating to "http://playwright.dev", waiting until "load"
[ERROR] 2021-03-07T08:35:32.264Z pw:api   navigated to "https://playwright.dev/"
[ERROR] 2021-03-07T08:35:32.644Z pw:api   "domcontentloaded" event fired
2021-03-07T08:35:30.714Z pw:api => BrowserType.launch started
2021-03-07T08:35:31.545Z pw:api <= BrowserType.launch succeeded
2021-03-07T08:35:31.547Z pw:api => Browser.newContext started
2021-03-07T08:35:31.565Z pw:api <= Browser.newContext succeeded
2021-03-07T08:35:31.566Z pw:api => BrowserContext.newPage started
2021-03-07T08:35:31.690Z pw:api <= BrowserContext.newPage succeeded
2021-03-07T08:35:31.691Z pw:api => Page.navigate started
2021-03-07T08:35:40.108Z pw:api <= Page.navigate failed
[ERROR] com.microsoft.playwright.PlaywrightException:
Error {
  message='Navigation failed because page crashed!
=========================== logs ===========================
navigating to "http://playwright.dev", waiting until "load"
============================================================
Note: use DEBUG=pw:api environment variable to capture Playwright logs.
  name='Error
  stack='Error: Navigation failed because page crashed!
=========================== logs ===========================
navigating to "http://playwright.dev", waiting until "load"
============================================================
Note: use DEBUG=pw:api environment variable to capture Playwright logs.
    at /tmp/playwright-java-6854617622148487159/package/lib/server/frames.js:414:64

Playwright.close() should not throw Exception

Exception is not specific enough.

The method actually throws IOException and InterruptedException.

But IOException is caught and rethrown as PlaywrightException by Playwright.create(), so it would be logical to be consistent and to do the same thing in close().

Regarding the InterruptedException, it's only thrown if the wait for the end of the driver process is being interrupted. But since the method ignores such failures anyway after a timeout, it would also seem logical to catch the InterruptedException, set back the interrupt status of the thread, and ignore the exception:

boolean didClose = false;
try {
  didClose = driverProcess.waitFor(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
  // reset the interrupted status of the thread so that callers higher on the stack know the thread has been interrupted
  Thread.currentThread().interrupt();
}
if (!didClose) {
  System.err.println("WARNING: Timed out/Interrupted while waiting for driver process to exit");
}

[Question] "Failed to find playwright-cli " exception for execution via "java -jar " command

After packaging the example project which is https://github.com/microsoft/playwright-java/tree/master/examples, it is not possible to execute via java -jar . It cause the exception mentioned below:

Caused by: java.lang.RuntimeException: Failed to find playwright-cli
	at com.microsoft.playwright.impl.Driver.ensureDriverInstalled(Driver.java:46) ~[driver-0.171.0.jar!/:na]
	at com.microsoft.playwright.impl.PlaywrightImpl.create(PlaywrightImpl.java:38) ~[playwright-0.171.0.jar!/:na]
	at com.microsoft.playwright.Playwright.create(Playwright.java:25) ~[playwright-0.171.0.jar!/:na]

[Question] Would it be possible to share a browser between different threads?

Hi there, we are very excited about this development

We have several tasks to do with many urls from different websites, my question is if we can have several browsers with several tasks and interact with them from different threads. It would be great that a thread operates in a tab of a shared browser. I think it's not possible because of https://github.com/microsoft/playwright-java#is-playwright-thread-safe

Is there any option to do it? Any ideas?

Thanks a lot for your answer

[Feature] Method withDevice missing in LaunchPersistentContextOptions

Hello there,

We have found that withDevice method is available in NewContextOptions class but not in LaunchPersistentContextOptions class. It's not very important because you can set the properties as well, but maybe it would be interesting to have this method in both classes

Kind regards

[Question] does playwright object design to be thread safety?

I found that when doing operation with the same playwright object under multi-thread may throw PlaywrightException: Object doesn't exist: BrowserContext@3453a9326319bd981cb8ebe57b0c34d2 or PlaywrightException: Cannot find command to respond,

PlaywrightException: Object doesn't exist's cause seems like that every component create by the same playwright object should register to the same connection object by Connection.registerObject()

and connection use a HashMap to do so, but HashMap is not thread safety

when HashMap expand its size under multi-thread, some data will lose

and PlaywrightException: Cannot find command to respond seems to be caused by the same reason, that Connection.internalSendMessage() put the message in the callbacks attribute which is a HashMap

test code like this:

 public static void main(String[] args) throws Exception {
        var playwright = Playwright.create();
        var browser = playwright.firefox().launch(new BrowserType.LaunchOptions().withHeadless(true));
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                // create the component, seems it will be registered in the connection object
                var context = browser.newContext();
                System.out.println("create ok");
                // use the component, it will get from the connection object but not found
                context.cookies("http://www.bing.com");
            }).start();
        }
        Thread.sleep(30000);
        playwright.close();
    }

(I'm not a native English speaker, and I'm a beginner of coding so if there something wrong, please tell me, Thanks!)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.