1
0
mirror of synced 2026-05-22 18:53:15 +00:00

feat: extend AutoCloseable in Playwright, BrowserContext, Browser and… (#238)

This commit is contained in:
JB Nizet
2021-02-02 02:31:51 +01:00
committed by GitHub
parent 5af091880f
commit a6f25595f3
13 changed files with 175 additions and 145 deletions
+52 -60
View File
@@ -64,23 +64,22 @@ import java.util.Arrays;
import java.util.List;
public class PageScreenshot {
public static void main(String[] args) throws Exception {
Playwright playwright = Playwright.create();
List<BrowserType> browserTypes = Arrays.asList(
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) {
Browser browser = browserType.launch();
BrowserContext context = browser.newContext(
new Browser.NewContextOptions().withViewport(800, 600));
Page page = context.newPage();
page.navigate("http://whatsmyuseragent.org/");
page.screenshot(new Page.ScreenshotOptions().withPath(Paths.get("screenshot-" + browserType.name() + ".png")));
browser.close();
);
for (BrowserType browserType : browserTypes) {
try (Browser browser = browserType.launch();
BrowserContext context = browser.newContext(new Browser.NewContextOptions().withViewport(800, 600));
Page page = context.newPage()) {
page.navigate("http://whatsmyuseragent.org/");
page.screenshot(new Page.ScreenshotOptions().withPath(Paths.get("screenshot-" + browserType.name() + ".png")));
}
}
}
playwright.close();
}
}
```
@@ -92,25 +91,22 @@ This snippet emulates Mobile Chromium on a device at a given geolocation, naviga
```java
import com.microsoft.playwright.*;
import java.nio.file.Paths;
import static java.util.Arrays.asList;
import java.util.Arrays;
public class MobileAndGeolocation {
public static void main(String[] args) throws Exception {
Playwright playwright = Playwright.create();
BrowserType browserType = playwright.chromium();
Browser browser = browserType.launch(new BrowserType.LaunchOptions().withHeadless(false));
DeviceDescriptor pixel2 = playwright.devices().get("Pixel 2");
BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.withDevice(pixel2)
.withLocale("en-US")
.withGeolocation(new Geolocation(41.889938, 12.492507))
.withPermissions(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().withPath(Paths.get("colosseum-pixel2.png")));
browser.close();
playwright.close();
public static void main(String[] args) {
try (Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().withHeadless(false));
BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.withDevice(playwright.devices().get("Pixel 2"))
.withLocale("en-US")
.withGeolocation(new Geolocation(41.889938, 12.492507))
.withPermissions(Arrays.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().withPath(Paths.get("colosseum-pixel2.png")));
}
}
}
```
@@ -123,23 +119,21 @@ This code snippet navigates to example.com in Firefox, and executes a script in
import com.microsoft.playwright.*;
public class EvaluateInBrowserContext {
public static void main(String[] args) throws Exception {
Playwright playwright = Playwright.create();
BrowserType browserType = playwright.firefox();
Browser browser = browserType.launch(new BrowserType.LaunchOptions().withHeadless(false));
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);
browser.close();
playwright.close();
public static void main(String[] args) {
try (Playwright playwright = Playwright.create();
Browser browser = playwright.firefox().launch(new BrowserType.LaunchOptions().withHeadless(false));
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);
}
}
}
```
@@ -152,19 +146,17 @@ This code snippet sets up request routing for a WebKit page to log all network r
import com.microsoft.playwright.*;
public class InterceptNetworkRequests {
public static void main(String[] args) throws Exception {
Playwright playwright = Playwright.create();
BrowserType browserType = playwright.webkit();
Browser browser = browserType.launch();
BrowserContext context = browser.newContext();
Page page = context.newPage();
page.route("**", route -> {
System.out.println(route.request().url());
route.continue_();
});
page.navigate("http://todomvc.com");
browser.close();
playwright.close();
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.continue_();
});
page.navigate("http://todomvc.com");
}
}
}
```
@@ -19,22 +19,20 @@ package org.example;
import com.microsoft.playwright.*;
public class EvaluateInBrowserContext {
public static void main(String[] args) throws Exception {
Playwright playwright = Playwright.create();
BrowserType browserType = playwright.firefox();
Browser browser = browserType.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);
browser.close();
playwright.close();
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);
}
}
}
@@ -19,18 +19,16 @@ package org.example;
import com.microsoft.playwright.*;
public class InterceptNetworkRequests {
public static void main(String[] args) throws Exception {
Playwright playwright = Playwright.create();
BrowserType browserType = playwright.webkit();
Browser browser = browserType.launch();
BrowserContext context = browser.newContext();
Page page = context.newPage();
page.route("**", route -> {
System.out.println(route.request().url());
route.continue_();
});
page.navigate("http://todomvc.com");
browser.close();
playwright.close();
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.continue_();
});
page.navigate("http://todomvc.com");
}
}
}
@@ -23,21 +23,18 @@ import java.nio.file.Paths;
import static java.util.Arrays.asList;
public class MobileAndGeolocation {
public static void main(String[] args) throws Exception {
Playwright playwright = Playwright.create();
BrowserType browserType = playwright.chromium();
Browser browser = browserType.launch(new BrowserType.LaunchOptions().withHeadless(false));
DeviceDescriptor pixel2 = playwright.devices().get("Pixel 2");
BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.withDevice(pixel2)
.withLocale("en-US")
.withGeolocation(new Geolocation(41.889938, 12.492507))
.withPermissions(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().withPath(Paths.get("colosseum-pixel2.png")));
browser.close();
playwright.close();
public static void main(String[] args) {
try (Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().withHeadless(false));
BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.withDevice(playwright.devices().get("Pixel 2"))
.withLocale("en-US")
.withGeolocation(new Geolocation(41.889938, 12.492507))
.withPermissions(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().withPath(Paths.get("colosseum-pixel2.png")));
}
}
}
@@ -23,22 +23,21 @@ import java.util.Arrays;
import java.util.List;
public class PageScreenshot {
public static void main(String[] args) throws Exception {
Playwright playwright = Playwright.create();
List<BrowserType> browserTypes = Arrays.asList(
playwright.chromium(),
playwright.webkit(),
playwright.firefox()
);
for (BrowserType browserType : browserTypes) {
Browser browser = browserType.launch();
BrowserContext context = browser.newContext(
new Browser.NewContextOptions().withViewport(800, 600));
Page page = context.newPage();
page.navigate("http://whatsmyuseragent.org/");
page.screenshot(new Page.ScreenshotOptions().withPath(Paths.get("screenshot-" + browserType.name() + ".png")));
browser.close();
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(new Browser.NewContextOptions().withViewport(800, 600));
Page page = context.newPage()) {
page.navigate("http://whatsmyuseragent.org/");
page.screenshot(new Page.ScreenshotOptions().withPath(Paths.get("screenshot-" + browserType.name() + ".png")));
}
}
}
playwright.close();
}
}
@@ -25,7 +25,7 @@ import java.util.function.Consumer;
*
* <p> A Browser is created via [{@code method: BrowserType.launch}]. An example of using a {@code Browser} to create a {@code Page}:
*/
public interface Browser {
public interface Browser extends AutoCloseable {
class VideoSize {
private final int width;
private final int height;
@@ -33,7 +33,7 @@ import java.util.regex.Pattern;
* <p> Playwright allows creation of "incognito" browser contexts with {@code browser.newContext()} method. "Incognito" browser
* contexts don't write any browsing data to disk.
*/
public interface BrowserContext {
public interface BrowserContext extends AutoCloseable {
enum SameSite { STRICT, LAX, NONE }
class HTTPCredentials {
@@ -35,7 +35,7 @@ import java.util.regex.Pattern;
*
* <p> To unsubscribe from events use the {@code removeListener} method:
*/
public interface Page {
public interface Page extends AutoCloseable {
class Viewport {
private final int width;
private final int height;
@@ -23,7 +23,7 @@ import java.util.*;
* Playwright module provides a method to launch a browser instance. The following is a typical example of using Playwright
* to drive automation:
*/
public interface Playwright {
public interface Playwright extends AutoCloseable {
/**
* This object can be used to launch or connect to Chromium, returning instances of {@code ChromiumBrowser}.
*/
@@ -0,0 +1,36 @@
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.playwright;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/**
* This test simply makes sure that all 4 main interfaces implement AutoCloseable. If it compiles, then it passes.
*/
public class TestAutoClose {
@Test
void shouldAllowUsingTryWithResources() throws Exception {
try (Playwright playwright = Playwright.create();
Browser browser = Utils.getBrowserTypeFromEnv(playwright).launch();
BrowserContext context = browser.newContext();
Page page = context.newPage()) {
assertEquals(2021, page.evaluate("() => 2021"));
}
}
}
@@ -63,23 +63,8 @@ public class TestBase {
static void launchBrowser(BrowserType.LaunchOptions launchOptions) {
playwright = Playwright.create();
String browserName = System.getenv("BROWSER");
if (browserName == null) {
browserName = "chromium";
}
switch (browserName) {
case "webkit":
browserType = playwright.webkit();
break;
case "firefox":
browserType = playwright.firefox();
break;
case "chromium":
browserType = playwright.chromium();
break;
default:
throw new IllegalArgumentException("Unknown browser: " + browserName);
}
browserType = Utils.getBrowserTypeFromEnv(playwright);
browser = browserType.launch(launchOptions);
}
@@ -103,4 +103,23 @@ class Utils {
return Arrays.asList("SSL_ERROR_UNKNOWN");
}
}
static BrowserType getBrowserTypeFromEnv(Playwright playwright) {
String browserName = System.getenv("BROWSER");
if (browserName == null) {
browserName = "chromium";
}
switch (browserName) {
case "webkit":
return playwright.webkit();
case "firefox":
return playwright.firefox();
case "chromium":
return playwright.chromium();
default:
throw new IllegalArgumentException("Unknown browser: " + browserName);
}
}
}
@@ -24,6 +24,7 @@ import com.google.gson.JsonObject;
import java.io.*;
import java.nio.file.FileSystems;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.Arrays.asList;
import static java.util.Collections.reverse;
@@ -994,6 +995,7 @@ class Interface extends TypeDefinition {
"package com.microsoft.playwright;\n";
private static Set<String> allowedBaseInterfaces = new HashSet<>(asList("Browser", "JSHandle", "BrowserContext"));
private static Set<String> autoCloseableInterfaces = new HashSet<>(asList("Playwright", "Browser", "BrowserContext", "Page"));
Interface(JsonObject jsonElement) {
super(null, jsonElement);
@@ -1043,13 +1045,17 @@ class Interface extends TypeDefinition {
}
output.add("");
String implementsClause = "";
List<String> superInterfaces = new ArrayList<>();
if (jsonElement.getAsJsonObject().has("extends")) {
String base = jsonElement.getAsJsonObject().get("extends").getAsString();
if (allowedBaseInterfaces.contains(base)) {
implementsClause = " extends " + base;
superInterfaces.add(base);
}
}
if (autoCloseableInterfaces.contains(jsonName)) {
superInterfaces.add("AutoCloseable");
}
String implementsClause = superInterfaces.isEmpty() ? "" : " extends " + String.join(", ", superInterfaces);
writeJavadoc(output, offset, formattedComment());
output.add("public interface " + jsonName + implementsClause + " {");