cherry-pick(release-1.9): rename with* to set* for java (#5739)

This commit is contained in:
Yury Semikhatsky 2021-03-05 14:17:03 -08:00 committed by GitHub
parent 097f7c3fc0
commit 07438f6149
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 341 additions and 124 deletions

View file

@ -308,7 +308,7 @@ public class Example {
public static void main(String[] args) { public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) { try (Playwright playwright = Playwright.create()) {
BrowserType webkit = playwright.webkit() BrowserType webkit = playwright.webkit()
Browser browser = webkit.launch(new BrowserType.LaunchOptions().withHeadless(false)); Browser browser = webkit.launch(new BrowserType.LaunchOptions().setHeadless(false));
BrowserContext context = browser.newContext(); BrowserContext context = browser.newContext();
context.exposeBinding("pageURL", (source, args) -> source.page().url()); context.exposeBinding("pageURL", (source, args) -> source.page().url());
Page page = context.newPage(); Page page = context.newPage();
@ -396,7 +396,7 @@ context.exposeBinding("clicked", (source, args) -> {
ElementHandle element = (ElementHandle) args[0]; ElementHandle element = (ElementHandle) args[0];
System.out.println(element.textContent()); System.out.println(element.textContent());
return null; return null;
}, new BrowserContext.ExposeBindingOptions().withHandle(true)); }, new BrowserContext.ExposeBindingOptions().setHandle(true));
page.setContent("" + page.setContent("" +
"<script>\n" + "<script>\n" +
" document.addEventListener('click', event => window.clicked(event.target));\n" + " document.addEventListener('click', event => window.clicked(event.target));\n" +
@ -495,7 +495,7 @@ public class Example {
public static void main(String[] args) { public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) { try (Playwright playwright = Playwright.create()) {
BrowserType webkit = playwright.webkit() BrowserType webkit = playwright.webkit()
Browser browser = webkit.launch(new BrowserType.LaunchOptions().withHeadless(false)); Browser browser = webkit.launch(new BrowserType.LaunchOptions().setHeadless(false));
context.exposeFunction("sha1", args -> { context.exposeFunction("sha1", args -> {
String text = (String) args[0]; String text = (String) args[0];
MessageDigest crypto; MessageDigest crypto;

View file

@ -143,7 +143,7 @@ const browser = await chromium.launch({ // Or 'firefox' or 'webkit'.
```java ```java
// Or "firefox" or "webkit". // Or "firefox" or "webkit".
Browser browser = chromium.launch(new BrowserType.LaunchOptions() Browser browser = chromium.launch(new BrowserType.LaunchOptions()
.withIgnoreDefaultArgs(Arrays.asList("--mute-audio"))); .setIgnoreDefaultArgs(Arrays.asList("--mute-audio")));
``` ```
```python async ```python async

View file

@ -601,7 +601,7 @@ handle.selectOption(['red', 'green', 'blue']);
// single selection matching the value // single selection matching the value
handle.selectOption("blue"); handle.selectOption("blue");
// single selection matching the label // single selection matching the label
handle.selectOption(new SelectOption().withLabel("Blue")); handle.selectOption(new SelectOption().setLabel("Blue"));
// multiple selection // multiple selection
handle.selectOption(new String[] {"red", "green", "blue"}); handle.selectOption(new String[] {"red", "green", "blue"});
``` ```
@ -707,7 +707,7 @@ await elementHandle.type('World', {delay: 100}); // Types slower, like a user
```java ```java
elementHandle.type("Hello"); // Types instantly elementHandle.type("Hello"); // Types instantly
elementHandle.type("World", new ElementHandle.TypeOptions().withDelay(100)); // Types slower, like a user elementHandle.type("World", new ElementHandle.TypeOptions().setDelay(100)); // Types slower, like a user
``` ```
```python async ```python async
@ -829,7 +829,7 @@ page.setContent("<div><span></span></div>");
ElementHandle div = page.querySelector("div"); ElementHandle div = page.querySelector("div");
// Waiting for the "span" selector relative to the div. // Waiting for the "span" selector relative to the div.
ElementHandle span = div.waitForSelector("span", new ElementHandle.WaitForSelectorOptions() ElementHandle span = div.waitForSelector("span", new ElementHandle.WaitForSelectorOptions()
.withState(WaitForSelectorState.ATTACHED)); .setState(WaitForSelectorState.ATTACHED));
``` ```
```python async ```python async

View file

@ -929,7 +929,7 @@ frame.selectOption('select#colors', 'red', 'green', 'blue');
// single selection matching the value // single selection matching the value
frame.selectOption("select#colors", "blue"); frame.selectOption("select#colors", "blue");
// single selection matching both the value and the label // single selection matching both the value and the label
frame.selectOption("select#colors", new SelectOption().withLabel("Blue")); frame.selectOption("select#colors", new SelectOption().setLabel("Blue"));
// multiple selection // multiple selection
frame.selectOption("select#colors", new String[] {"red", "green", "blue"}); frame.selectOption("select#colors", new String[] {"red", "green", "blue"});
``` ```
@ -1047,7 +1047,7 @@ await frame.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a
// Types instantly // Types instantly
frame.type("#mytextarea", "Hello"); frame.type("#mytextarea", "Hello");
// Types slower, like a user // Types slower, like a user
frame.type("#mytextarea", "World", new Frame.TypeOptions().withDelay(100)); frame.type("#mytextarea", "World", new Frame.TypeOptions().setDelay(100));
``` ```
```python async ```python async

View file

@ -210,11 +210,11 @@ await browser.close();
Page page = browser.newPage(); Page page = browser.newPage();
page.navigate("https://keycode.info"); page.navigate("https://keycode.info");
page.keyboard().press("A"); page.keyboard().press("A");
page.screenshot(new Page.ScreenshotOptions().withPath(Paths.get("A.png")); page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("A.png"));
page.keyboard().press("ArrowLeft"); page.keyboard().press("ArrowLeft");
page.screenshot(new Page.ScreenshotOptions().withPath(Paths.get("ArrowLeft.png"))); page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("ArrowLeft.png")));
page.keyboard().press("Shift+O"); page.keyboard().press("Shift+O");
page.screenshot(new Page.ScreenshotOptions().withPath(Paths.get("O.png"))); page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("O.png")));
browser.close(); browser.close();
``` ```
@ -269,7 +269,7 @@ await page.keyboard.type('World', {delay: 100}); // Types slower, like a user
// Types instantly // Types instantly
page.keyboard().type("Hello"); page.keyboard().type("Hello");
// Types slower, like a user // Types slower, like a user
page.keyboard().type("World", new Keyboard.TypeOptions().withDelay(100)); page.keyboard().type("World", new Keyboard.TypeOptions().setDelay(100));
``` ```
```python async ```python async

View file

@ -31,7 +31,7 @@ public class Example {
BrowserContext context = browser.newContext(); BrowserContext context = browser.newContext();
Page page = context.newPage(); Page page = context.newPage();
page.navigate("https://example.com"); page.navigate("https://example.com");
page.screenshot(new Page.ScreenshotOptions().withPath(Paths.get("screenshot.png"))); page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot.png")));
browser.close(); browser.close();
} }
} }
@ -744,7 +744,7 @@ page.evaluate("() => matchMedia('screen').matches");
page.evaluate("() => matchMedia('print').matches"); page.evaluate("() => matchMedia('print').matches");
// → false // → false
page.emulateMedia(new Page.EmulateMediaOptions().withMedia(Media.PRINT)); page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.PRINT));
page.evaluate("() => matchMedia('screen').matches"); page.evaluate("() => matchMedia('screen').matches");
// → false // → false
page.evaluate("() => matchMedia('print').matches"); page.evaluate("() => matchMedia('print').matches");
@ -806,7 +806,7 @@ await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').ma
``` ```
```java ```java
page.emulateMedia(new Page.EmulateMediaOptions().withColorScheme(ColorScheme.DARK)); page.emulateMedia(new Page.EmulateMediaOptions().setColorScheme(ColorScheme.DARK));
page.evaluate("() => matchMedia('(prefers-color-scheme: dark)').matches"); page.evaluate("() => matchMedia('(prefers-color-scheme: dark)').matches");
// → true // → true
page.evaluate("() => matchMedia('(prefers-color-scheme: light)').matches"); page.evaluate("() => matchMedia('(prefers-color-scheme: light)').matches");
@ -1250,7 +1250,7 @@ page.exposeBinding("clicked", (source, args) -> {
ElementHandle element = (ElementHandle) args[0]; ElementHandle element = (ElementHandle) args[0];
System.out.println(element.textContent()); System.out.println(element.textContent());
return null; return null;
}, new Page.ExposeBindingOptions().withHandle(true)); }, new Page.ExposeBindingOptions().setHandle(true));
page.setContent("" + page.setContent("" +
"<script>\n" + "<script>\n" +
" document.addEventListener('click', event => window.clicked(event.target));\n" + " document.addEventListener('click', event => window.clicked(event.target));\n" +
@ -1786,8 +1786,8 @@ await page.pdf({path: 'page.pdf'});
```java ```java
// Generates a PDF with "screen" media type. // Generates a PDF with "screen" media type.
page.emulateMedia(new Page.EmulateMediaOptions().withMedia(Media.SCREEN)); page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.SCREEN));
page.pdf(new Page.PdfOptions().withPath(Paths.get("page.pdf"))); page.pdf(new Page.PdfOptions().setPath(Paths.get("page.pdf")));
``` ```
```python async ```python async
@ -1975,11 +1975,11 @@ await browser.close();
Page page = browser.newPage(); Page page = browser.newPage();
page.navigate("https://keycode.info"); page.navigate("https://keycode.info");
page.press("body", "A"); page.press("body", "A");
page.screenshot(new Page.ScreenshotOptions().withPath(Paths.get("A.png"))); page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("A.png")));
page.press("body", "ArrowLeft"); page.press("body", "ArrowLeft");
page.screenshot(new Page.ScreenshotOptions().withPath(Paths.get("ArrowLeft.png" ))); page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("ArrowLeft.png" )));
page.press("body", "Shift+O"); page.press("body", "Shift+O");
page.screenshot(new Page.ScreenshotOptions().withPath(Paths.get("O.png" ))); page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("O.png" )));
``` ```
```python async ```python async
@ -2224,7 +2224,7 @@ page.selectOption('select#colors', ['red', 'green', 'blue']);
// single selection matching the value // single selection matching the value
page.selectOption("select#colors", "blue"); page.selectOption("select#colors", "blue");
// single selection matching both the value and the label // single selection matching both the value and the label
page.selectOption("select#colors", new SelectOption().withLabel("Blue")); page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
// multiple selection // multiple selection
page.selectOption("select#colors", new String[] {"red", "green", "blue"}); page.selectOption("select#colors", new String[] {"red", "green", "blue"});
``` ```
@ -2444,7 +2444,7 @@ await page.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a u
// Types instantly // Types instantly
page.type("#mytextarea", "Hello"); page.type("#mytextarea", "Hello");
// Types slower, like a user // Types slower, like a user
page.type("#mytextarea", "World", new Page.TypeOptions().withDelay(100)); page.type("#mytextarea", "World", new Page.TypeOptions().setDelay(100));
``` ```
```python async ```python async

View file

@ -54,7 +54,7 @@ page.route("**/*", route -> {
Map<String, String> headers = new HashMap<>(route.request().headers()); Map<String, String> headers = new HashMap<>(route.request().headers());
headers.put("foo", "bar"); // set "foo" header headers.put("foo", "bar"); // set "foo" header
headers.remove("origin"); // remove "origin" header headers.remove("origin"); // remove "origin" header
route.resume(new Route.ResumeOptions().withHeaders(headers)); route.resume(new Route.ResumeOptions().setHeaders(headers));
}); });
``` ```
@ -123,9 +123,9 @@ await page.route('**/*', route => {
```java ```java
page.route("**/*", route -> { page.route("**/*", route -> {
route.fulfill(new Route.FulfillOptions() route.fulfill(new Route.FulfillOptions()
.withStatus(404) .setStatus(404)
.withContentType("text/plain") .setContentType("text/plain")
.withBody("Not Found!")); .setBody("Not Found!"));
}); });
``` ```
@ -151,7 +151,7 @@ await page.route('**/xhr_endpoint', route => route.fulfill({ path: 'mock_data.js
```java ```java
page.route("**/xhr_endpoint", route -> route.fulfill( page.route("**/xhr_endpoint", route -> route.fulfill(
new Route.FulfillOptions().withPath(Paths.get("mock_data.json"))); new Route.FulfillOptions().setPath(Paths.get("mock_data.json")));
``` ```
```python async ```python async

View file

@ -106,7 +106,7 @@ System.getenv().put("STORAGE", storage);
// Create a new context with the saved storage state // Create a new context with the saved storage state
BrowserContext context = browser.newContext( BrowserContext context = browser.newContext(
new Browser.NewContextOptions().withStorageState(storage)); new Browser.NewContextOptions().setStorageState(storage));
``` ```
```python async ```python async
@ -261,7 +261,7 @@ public class Example {
BrowserType chromium = playwright.chromium(); BrowserType chromium = playwright.chromium();
Path userDataDir = Paths.get("/path/to/directory"); Path userDataDir = Paths.get("/path/to/directory");
BrowserContext context = chromium.launchPersistentContext(userDataDir, BrowserContext context = chromium.launchPersistentContext(userDataDir,
new BrowserType.LaunchPersistentContextOptions().withHeadless(false)); new BrowserType.LaunchPersistentContextOptions().setHeadless(false));
// Execute login steps manually in the browser window // Execute login steps manually in the browser window
} }
} }

View file

@ -85,7 +85,7 @@ Suggested configuration
```java ```java
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions() Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
.withArgs(Arrays.asList("--disable-dev-shm-usage"))); .setArgs(Arrays.asList("--disable-dev-shm-usage")));
``` ```
```python async ```python async
@ -245,7 +245,7 @@ public class Example {
public static void main(String[] args) { public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) { try (Playwright playwright = Playwright.create()) {
BrowserType chromium = playwright.chromium(); BrowserType chromium = playwright.chromium();
Browser browser = chromium.launch(new BrowserType.LaunchOptions().withChromiumSandbox(false)); Browser browser = chromium.launch(new BrowserType.LaunchOptions().setChromiumSandbox(false));
} }
} }
} }
@ -345,7 +345,7 @@ public class Example {
public static void main(String[] args) { public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) { try (Playwright playwright = Playwright.create()) {
BrowserType chromium = playwright.chromium(); BrowserType chromium = playwright.chromium();
Browser browser = chromium.launch(new BrowserType.LaunchOptions().withHeadless(false)); Browser browser = chromium.launch(new BrowserType.LaunchOptions().setHeadless(false));
} }
} }
} }

View file

@ -100,7 +100,7 @@ public class Example {
try (Playwright playwright = Playwright.create()) { try (Playwright playwright = Playwright.create()) {
BrowserType chromium = playwright.chromium(); BrowserType chromium = playwright.chromium();
// Make sure to run headed. // Make sure to run headed.
Browser browser = chromium.launch(new BrowserType.LaunchOptions().withHeadless(false)); Browser browser = chromium.launch(new BrowserType.LaunchOptions().setHeadless(false));
// Setup context however you like. // Setup context however you like.
BrowserContext context = browser.newContext(/* pass any options */); BrowserContext context = browser.newContext(/* pass any options */);
context.route("**/*", route -> route.resume()); context.route("**/*", route -> route.resume());

View file

@ -36,7 +36,7 @@ public class Example {
public static void main(String[] args) { public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) { try (Playwright playwright = Playwright.create()) {
BrowserType chromium = playwright.chromium(); BrowserType chromium = playwright.chromium();
Browser browser = chromium.launch(new BrowserType.LaunchOptions().withHeadless(false)); Browser browser = chromium.launch(new BrowserType.LaunchOptions().setHeadless(false));
browser.close(); browser.close();
} }
} }
@ -123,15 +123,15 @@ public class Example {
try (Playwright playwright = Playwright.create()) { try (Playwright playwright = Playwright.create()) {
BrowserType devices = playwright.devices(); BrowserType devices = playwright.devices();
BrowserContext context = browser.newContext(new Browser.NewContextOptions() BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.withUserAgent("Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Mobile/15E148 Safari/604.1") .setUserAgent("Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Mobile/15E148 Safari/604.1")
.withViewportSize(375, 812) .setViewportSize(375, 812)
.withDeviceScaleFactor(3) .setDeviceScaleFactor(3)
.withIsMobile(true) .setIsMobile(true)
.withHasTouch(true) .setHasTouch(true)
.withPermissions(Arrays.asList("geolocation")) .setPermissions(Arrays.asList("geolocation"))
.withGeolocation(52.52, 13.39) .setGeolocation(52.52, 13.39)
.withColorScheme(ColorScheme.DARK) .setColorScheme(ColorScheme.DARK)
.withLocale("de-DE")); .setLocale("de-DE"));
} }
} }
} }
@ -564,7 +564,7 @@ await page.waitForSelector('#promo');
```java ```java
// Wait for #search to appear in the DOM. // Wait for #search to appear in the DOM.
page.waitForSelector("#search", new Page.WaitForSelectorOptions() page.waitForSelector("#search", new Page.WaitForSelectorOptions()
.withState(WaitForSelectorState.ATTACHED)); .setState(WaitForSelectorState.ATTACHED));
// Wait for #promo to become visible, for example with "visibility:visible". // Wait for #promo to become visible, for example with "visibility:visible".
page.waitForSelector("#promo"); page.waitForSelector("#promo");
``` ```
@ -595,10 +595,10 @@ await page.waitForSelector('#promo', { state: 'detached' });
```java ```java
// Wait for #details to become hidden, for example with "display:none". // Wait for #details to become hidden, for example with "display:none".
page.waitForSelector("#details", new Page.WaitForSelectorOptions() page.waitForSelector("#details", new Page.WaitForSelectorOptions()
.withState(WaitForSelectorState.HIDDEN)); .setState(WaitForSelectorState.HIDDEN));
// Wait for #promo to be removed from the DOM. // Wait for #promo to be removed from the DOM.
page.waitForSelector("#promo", new Page.WaitForSelectorOptions() page.waitForSelector("#promo", new Page.WaitForSelectorOptions()
.withState(WaitForSelectorState.DETACHED)); .setState(WaitForSelectorState.DETACHED));
``` ```
```python async ```python async

View file

@ -28,8 +28,8 @@ await chromium.launch({ headless: false, slowMo: 100 }); // or firefox, webkit
```java ```java
chromium.launch(new BrowserType.LaunchOptions() // or firefox, webkit chromium.launch(new BrowserType.LaunchOptions() // or firefox, webkit
.withHeadless(false) .setHeadless(false)
.withSlowMo(100)); .setSlowMo(100));
``` ```
```python async ```python async
@ -82,7 +82,7 @@ await chromium.launch({ devtools: true });
``` ```
```java ```java
chromium.launch(new BrowserType.LaunchOptions().withDevtools(true)); chromium.launch(new BrowserType.LaunchOptions().setDevtools(true));
``` ```
```python async ```python async

View file

@ -90,7 +90,7 @@ page.onDialog(dialog -> {
assertEquals("beforeunload", dialog.type()); assertEquals("beforeunload", dialog.type());
dialog.dismiss(); dialog.dismiss();
}); });
page.close(new Page.CloseOptions().withRunBeforeUnload(true)); page.close(new Page.CloseOptions().setRunBeforeUnload(true));
``` ```
```python async ```python async

View file

@ -82,7 +82,7 @@ const context = await browser.newContext({
```java ```java
BrowserContext context = browser.newContext(new Browser.NewContextOptions() BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.withUserAgent("My user agent")); .setUserAgent("My user agent"));
``` ```
```python async ```python async
@ -125,15 +125,15 @@ const context = await browser.newContext({
```java ```java
// Create context with given viewport // Create context with given viewport
BrowserContext context = browser.newContext(new Browser.NewContextOptions() BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.withViewportSize(1280, 1024)); .setViewportSize(1280, 1024));
// Resize viewport for individual page // Resize viewport for individual page
page.setViewportSize(1600, 1200); page.setViewportSize(1600, 1200);
// Emulate high-DPI // Emulate high-DPI
BrowserContext context = browser.newContext(new Browser.NewContextOptions() BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.withViewportSize(2560, 1440) .setViewportSize(2560, 1440)
.withDeviceScaleFactor(2); .setDeviceScaleFactor(2);
``` ```
```python async ```python async
@ -186,8 +186,8 @@ const context = await browser.newContext({
```java ```java
// Emulate locale and time // Emulate locale and time
BrowserContext context = browser.newContext(new Browser.NewContextOptions() BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.withLocale("de-DE") .setLocale("de-DE")
.withTimezoneId("Europe/Berlin")); .setTimezoneId("Europe/Berlin"));
``` ```
```python async ```python async
@ -223,7 +223,7 @@ const context = await browser.newContext({
```java ```java
BrowserContext context = browser.newContext(new Browser.NewContextOptions() BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.withPermissions(Arrays.asList("notifications")); .setPermissions(Arrays.asList("notifications"));
``` ```
```python async ```python async
@ -264,7 +264,7 @@ await context.grantPermissions(['notifications'], {origin: 'https://skype.com'}
```java ```java
context.grantPermissions(Arrays.asList("notifications"), context.grantPermissions(Arrays.asList("notifications"),
new BrowserContext.GrantPermissionsOptions().withOrigin("https://skype.com")); new BrowserContext.GrantPermissionsOptions().setOrigin("https://skype.com"));
``` ```
```python async ```python async
@ -313,8 +313,8 @@ const context = await browser.newContext({
```java ```java
BrowserContext context = browser.newContext(new Browser.NewContextOptions() BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.withGeolocation(48.858455, 2.294474) .setGeolocation(48.858455, 2.294474)
.withPermissions(Arrays.asList("geolocation"))); .setPermissions(Arrays.asList("geolocation")));
``` ```
```python async ```python async
@ -382,17 +382,17 @@ await page.emulateMedia({ media: 'print' });
```java ```java
// Create context with dark mode // Create context with dark mode
BrowserContext context = browser.newContext(new Browser.NewContextOptions() BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.withColorScheme(ColorScheme.DARK)); // or "light" .setColorScheme(ColorScheme.DARK)); // or "light"
// Create page with dark mode // Create page with dark mode
Page page = browser.newPage(new Browser.NewPageOptions() Page page = browser.newPage(new Browser.NewPageOptions()
.withColorScheme(ColorScheme.DARK)); // or "light" .setColorScheme(ColorScheme.DARK)); // or "light"
// Change color scheme for the page // Change color scheme for the page
page.emulateMedia(new Page.EmulateMediaOptions().withColorScheme(ColorScheme.DARK)); page.emulateMedia(new Page.EmulateMediaOptions().setColorScheme(ColorScheme.DARK));
// Change media for page // Change media for page
page.emulateMedia(new Page.EmulateMediaOptions().withMedia(Media.PRINT)); page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.PRINT));
``` ```
```python async ```python async

View file

@ -181,7 +181,7 @@ await page.selectOption('select#colors', option);
page.selectOption("select#colors", "blue"); page.selectOption("select#colors", "blue");
// Single selection matching the label // Single selection matching the label
page.selectOption("select#colors", new SelectOption().withLabel("Blue")); page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
// Multiple selected items // Multiple selected items
page.selectOption("select#colors", new String[] {"red", "green", "blue"}); page.selectOption("select#colors", new String[] {"red", "green", "blue"});
@ -261,16 +261,16 @@ page.click("button#submit");
page.dblclick("#item"); page.dblclick("#item");
// Right click // Right click
page.click("#item", new Page.ClickOptions().withButton(MouseButton.RIGHT)); page.click("#item", new Page.ClickOptions().setButton(MouseButton.RIGHT));
// Shift + click // Shift + click
page.click("#item", new Page.ClickOptions().withModifiers(Arrays.asList(KeyboardModifier.SHIFT))); page.click("#item", new Page.ClickOptions().setModifiers(Arrays.asList(KeyboardModifier.SHIFT)));
// Hover over element // Hover over element
page.hover("#item"); page.hover("#item");
// Click the top left corner // Click the top left corner
page.click("#item", new Page.ClickOptions().withPosition(0, 0)); page.click("#item", new Page.ClickOptions().setPosition(0, 0));
``` ```
```python async ```python async
@ -331,7 +331,7 @@ await page.click('button#submit', { force: true });
``` ```
```java ```java
page.click("button#submit", new Page.ClickOptions().withForce(true)); page.click("button#submit", new Page.ClickOptions().setForce(true));
``` ```
```python async ```python async

137
docs/src/intro-java.md Normal file
View file

@ -0,0 +1,137 @@
---
id: intro
title: "Getting Started"
---
<!-- TOC -->
- [Release notes](./release-notes.md)
## Installation
Playwright is distributed as a set of [Maven](https://maven.apache.org/what-is-maven.html) modules. The easiest way to use it is to add one dependency to your project's `pom.xml` as described below. If you're not familiar with Maven please refer to its [documentation](https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html).
## Usage
<Tabs
defaultValue="java"
values={[
{label: 'Example.java', value: 'java'},
{label: 'pom.xml', value: 'pom'}
]
}>
<TabItem value="java">
```java
package org.example;
import com.microsoft.playwright.*;
public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch();
Page page = browser.newPage();
page.navigate("http://playwright.dev");
System.out.println(page.title());
}
}
}
```
</TabItem>
<TabItem value="pom">
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>examples</artifactId>
<version>0.1-SNAPSHOT</version>
<name>Playwright Client Examples</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>0.190.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
```
</TabItem>
</Tabs>
With the Example.java and pom.xml above, compile and execute your new program as follows:
```sh
mvn compile exec:java -Dexec.mainClass="org.example.Example"
```
Running it downloads the Playwright package and installs browser binaries for Chromium, Firefox and WebKit. To modify this behavior see [installation parameters](./installation.md).
## First script
In our first script, we will navigate to `whatsmyuseragent.org` and take a screenshot in WebKit.
```java
import com.microsoft.playwright.*;
import java.nio.file.Paths;
public class WebKitScreenshot {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.webkit().launch();
Page page = browser.newPage();
page.navigate("http://whatsmyuseragent.org/");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("example.png")));
}
}
}
```
By default, Playwright runs the browsers in headless mode. To see the browser UI, pass the `headless=false` flag while launching the browser. You can also use [`option: slowMo`] to slow down execution. Learn more in the debugging tools [section](./debug.md).
```java
playwright.firefox().launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(50));
```
## Record scripts
Command Line Interface [CLI](./cli.md) can be used to record user interactions and generate Java code.
```sh
$ mvn exec:java -e -Dexec.mainClass=com.microsoft.playwright.CLI -Dexec.args="codegen wikipedia.org"
```
## System requirements
Playwright requires **Java 8** or newer. The browser binaries for Chromium,
Firefox and WebKit work across the 3 platforms (Windows, macOS, Linux):
* **Windows**: Works with Windows and Windows Subsystem for Linux (WSL).
* **macOS**: Requires 10.14 or above.
* **Linux**: Depending on your Linux distribution, you might need to install additional
dependencies to run the browsers.
* Firefox requires Ubuntu 18.04+
* For Ubuntu 18.04, the additional dependencies are defined in [our Docker image](https://github.com/microsoft/playwright/blob/master/utils/docker/Dockerfile.bionic),
which is based on Ubuntu.

View file

@ -68,7 +68,7 @@ await page.goto('https://example.com', { waitUntil: 'networkidle' });
```java ```java
// Navigate and wait until network is idle // Navigate and wait until network is idle
page.navigate("https://example.com", new Page.NavigateOptions() page.navigate("https://example.com", new Page.NavigateOptions()
.withWaitUntil(WaitUntilState.NETWORKIDLE)); .setWaitUntil(WaitUntilState.NETWORKIDLE));
``` ```
```python async ```python async
@ -313,7 +313,7 @@ await Promise.all([
```java ```java
// Running action in the callback of waitForNavigation prevents a race // Running action in the callback of waitForNavigation prevents a race
// condition between clicking and waiting for a navigation. // condition between clicking and waiting for a navigation.
page.waitForNavigation(new Page.WaitForNavigationOptions().withUrl("**/login"), () -> { page.waitForNavigation(new Page.WaitForNavigationOptions().setUrl("**/login"), () -> {
page.click("a"); // Triggers a navigation with a script redirect page.click("a"); // Triggers a navigation with a script redirect
}); });
``` ```

View file

@ -26,7 +26,7 @@ await page.goto('https://example.com');
```java ```java
BrowserContext context = browser.newContext(new Browser.NewContextOptions() BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.withHttpCredentials("bill", "pa55w0rd")); .setHttpCredentials("bill", "pa55w0rd"));
Page page = context.newPage(); Page page = context.newPage();
page.navigate("https://example.com"); page.navigate("https://example.com");
``` ```
@ -50,6 +50,79 @@ page.goto("https://example.com")
### API reference ### API reference
- [`method: Browser.newContext`] - [`method: Browser.newContext`]
## HTTP Proxy
You can configure pages to load over the HTTP(S) proxy or SOCKSv5. Proxy can be either set globally
for the entire browser, or for each browser context individually.
You can optionally specify username and password for HTTP(S) proxy, you can also specify hosts to
bypass proxy for.
Here is an example of a global proxy:
```js
const browser = await chromium.launch({
proxy: {
server: 'http://myproxy.com:3128',
user: 'usr',
password: 'pwd'
}
});
```
```java
Browser browser = chromium.launch(new BrowserType.LaunchOptions()
.setProxy(new Proxy("http://myproxy.com:3128")
.setUsername('usr')
.setPassword('pwd'));
```
```python async
browser = await chromium.launch(proxy={
"server": "http://myproxy.com:3128",
"user": "usr",
"password": "pwd"
})
```
```python sync
browser = chromium.launch(proxy={
"server": "http://myproxy.com:3128",
"user": "usr",
"password": "pwd"
})
```
When specifying proxy for each context individually, you need to give Playwright
a hint that proxy will be set. This is done via passing a non-empty proxy server
to the browser itself. Here is an example of a context-specific proxy:
```js
const browser = await chromium.launch({
proxy: { server: 'per-context' }
});
const context = await browser.newContext({
proxy: { server: 'http://myproxy.com:3128' }
})
```
```java
Browser browser = chromium.launch(new BrowserType.LaunchOptions()
.setProxy(new Proxy("per-context"));
BrowserContext context = chromium.launch(new Browser.NewContextOptions()
.setProxy(new Proxy("http://myproxy.com:3128"));
```
```python async
browser = await chromium.launch(proxy={"server": "per-context"})
context = await browser.new_context(proxy={"server": "http://myproxy.com:3128"})
```
```python sync
browser = chromium.launch(proxy={"server": "per-context"})
context = browser.new_context(proxy={"server": "http://myproxy.com:3128"})
```
## Network events ## Network events
You can monitor all the requests and responses: You can monitor all the requests and responses:
@ -232,8 +305,8 @@ await page.goto('https://example.com');
```java ```java
page.route("**/api/fetch_data", route -> route.fulfill(new Route.FulfillOptions() page.route("**/api/fetch_data", route -> route.fulfill(new Route.FulfillOptions()
.withStatus(200) .setStatus(200)
.withBody(testData))); .setBody(testData)));
page.navigate("https://example.com"); page.navigate("https://example.com");
``` ```
@ -268,8 +341,8 @@ await page.goto('https://example.com');
```java ```java
browserContext.route("**/api/login", route -> route.fulfill(new Route.FulfillOptions() browserContext.route("**/api/login", route -> route.fulfill(new Route.FulfillOptions()
.withStatus(200) .setStatus(200)
.withBody("accept"))); .setBody("accept")));
page.navigate("https://example.com"); page.navigate("https://example.com");
``` ```
@ -319,11 +392,11 @@ await page.route('**/*', route => route.continue({method: 'POST'}));
page.route("**/*", route -> { page.route("**/*", route -> {
Map<String, String> headers = new HashMap<>(route.request().headers()); Map<String, String> headers = new HashMap<>(route.request().headers());
headers.remove("X-Secret"); headers.remove("X-Secret");
route.resume(new Route.ResumeOptions().withHeaders(headers)); route.resume(new Route.ResumeOptions().setHeaders(headers));
}); });
// Continue requests as POST. // Continue requests as POST.
page.route("**/*", route -> route.resume(new Route.ResumeOptions().withMethod("POST"))); page.route("**/*", route -> route.resume(new Route.ResumeOptions().setMethod("POST")));
``` ```
```python async ```python async

View file

@ -32,8 +32,8 @@ await page.screenshot({ path: 'screenshot.png', fullPage: true });
```java ```java
page.screenshot(new Page.ScreenshotOptions() page.screenshot(new Page.ScreenshotOptions()
.withPath(Paths.get("screenshot.png")) .setPath(Paths.get("screenshot.png"))
.withFullPage(true)); .setFullPage(true));
``` ```
```python async ```python async
@ -80,7 +80,7 @@ await elementHandle.screenshot({ path: 'screenshot.png' });
```java ```java
ElementHandle elementHandle = page.querySelector(".header"); ElementHandle elementHandle = page.querySelector(".header");
elementHandle.screenshot(new ElementHandle.ScreenshotOptions().withPath(Paths.get("screenshot.png"))); elementHandle.screenshot(new ElementHandle.ScreenshotOptions().setPath(Paths.get("screenshot.png")));
``` ```
```python async ```python async

View file

@ -9,17 +9,32 @@ Playwright can record videos for all pages in a [browser context](./core-concept
upon context closure, so make sure to await [`method: BrowserContext.close`]. upon context closure, so make sure to await [`method: BrowserContext.close`].
```js ```js
// With browser.newContext()
const context = await browser.newContext({ recordVideo: { dir: 'videos/' } }); const context = await browser.newContext({ recordVideo: { dir: 'videos/' } });
// Make sure to await close, so that videos are saved. // Make sure to await close, so that videos are saved.
await context.close(); await context.close();
```
// With browser.newPage() ```java
const page = await browser.newPage({ recordVideo: { dir: 'videos/' } }); context = browser.newContext(new Browser.NewContextOptions().setRecordVideoDir(Paths.get("videos/")));
// Make sure to await close, so that videos are saved. // Make sure to close, so that videos are saved.
await page.close(); context.close();
```
// [Optional] Specify video size; defaults to viewport size scaled down to fit 800x800 ```python async
context = await browser.new_context(record_video_dir="videos/")
# Make sure to await close, so that videos are saved.
await context.close()
```
```python sync
context = browser.new_context(record_video_dir="videos/")
# Make sure to close, so that videos are saved.
context.close()
```
You can also specify video size, it defaults to viewport size scaled down to fit 800x800.
```js
const context = await browser.newContext({ const context = await browser.newContext({
recordVideo: { recordVideo: {
dir: 'videos/', dir: 'videos/',
@ -29,34 +44,12 @@ const context = await browser.newContext({
``` ```
```java ```java
// With browser.newContext()
context = browser.newContext(new Browser.NewContextOptions().withRecordVideoDir(Paths.get("videos/")));
// Make sure to close, so that videos are saved.
context.close();
// With browser.newPage()
Page page = browser.newPage(new Browser.NewPageOptions().withRecordVideoDir(Paths.get("videos/")));
// Make sure to close, so that videos are saved.
page.close();
// [Optional] Specify video size; defaults to viewport size scaled down to fit 800x800
BrowserContext context = browser.newContext(new Browser.NewContextOptions() BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.withRecordVideoDir(Paths.get("videos/")) .setRecordVideoDir(Paths.get("videos/"))
.withRecordVideoSize(1024, 768)); .setRecordVideoSize(1024, 768));
``` ```
```python async ```python async
# With browser.new_context()
context = await browser.new_context(record_video_dir="videos/")
# Make sure to await close, so that videos are saved.
await context.close()
# With browser.new_page()
page = await browser.new_page(record_video_dir="videos/")
# Make sure to await close, so that videos are saved.
await page.close()
# [Optional] specify video size; defaults to viewport size scaled down to fit 800x800
context = await browser.new_context( context = await browser.new_context(
record_video_dir="videos/", record_video_dir="videos/",
record_video_size={"width": 1024, "height": 768} record_video_size={"width": 1024, "height": 768}
@ -64,23 +57,37 @@ context = await browser.new_context(
``` ```
```python sync ```python sync
# With browser.new_context()
context = browser.new_context(record_video_dir="videos/")
# Make sure to close, so that videos are saved.
context.close()
# With browser.new_page()
page = browser.new_page(record_video_dir="videos/")
# Make sure to close, so that videos are saved.
page.close()
# [Optional] specify video size; defaults to viewport size scaled down to fit 800x800
context = browser.new_context( context = browser.new_context(
record_video_dir="videos/", record_video_dir="videos/",
record_video_size={"width": 1024, "height": 768} record_video_size={"width": 1024, "height": 768}
) )
``` ```
Saved video files will appear in the specified folder. They all have generated unique names.
For the multi-page scenarios, you can access the video file associated with the page via the
[`method: Page.video`].
```js
const path = await page.video().path();
```
```java
path = page.video().path();
```
```python async
path = await page.video.path()
```
```python sync
path = page.video.path()
```
:::note
Note that the video is only available after the page or browser context is closed.
:::
### API reference ### API reference
- [BrowserContext] - [BrowserContext]
- [`method: Browser.newContext`] - [`method: Browser.newContext`]