chore: roll driver to 1.38.0-alpha-aug-23 (#1362)

Reference https://github.com/microsoft/playwright-java/issues/1353
This commit is contained in:
Yury Semikhatsky 2023-08-23 18:41:40 -07:00 committed by GitHub
parent 7d5953c96e
commit fa75e29fcf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
25 changed files with 390 additions and 157 deletions

View File

@ -127,6 +127,16 @@ public interface BrowserContext extends AutoCloseable {
*/
void offPage(Consumer<Page> handler);
/**
* Emitted when unhandled exceptions occur on any pages created through this context. To only listen for {@code pageError}
* events from a particular page, use {@link Page#onPageError Page.onPageError()}.
*/
void onPageError(Consumer<PageError> handler);
/**
* Removes handler that was previously added with {@link #onPageError onPageError(handler)}.
*/
void offPageError(Consumer<PageError> handler);
/**
* Emitted when a request is issued from any pages created through this context. The [request] object is read-only. To only
* listen for requests from a particular page, use {@link Page#onRequest Page.onRequest()}.

View File

@ -24,14 +24,16 @@ import java.nio.file.Path;
*
* <p> All the downloaded files belonging to the browser context are deleted when the browser context is closed.
*
* <p> Download event is emitted once the download starts. Download path becomes available once download completes:
* <p> Download event is emitted once the download starts. Download path becomes available once download completes.
* <pre>{@code
* // wait for download to start
* // Wait for the download to start
* Download download = page.waitForDownload(() -> {
* page.getByText("Download file").click();
* // Perform the action that initiates download
* page.getByText("Download file").click();
* });
* // wait for download to complete
* Path path = download.path();
*
* // Wait for the download process to complete and save the downloaded file somewhere
* download.saveAs(Paths.get("/path/to/save/at/", download.suggestedFilename()));
* }</pre>
*/
public interface Download {
@ -80,6 +82,11 @@ public interface Download {
* Copy the download to a user-specified path. It is safe to call this method while the download is still in progress. Will
* wait for the download to finish if necessary.
*
* <p> **Usage**
* <pre>{@code
* download.saveAs(Paths.get("/path/to/save/at/", download.suggestedFilename()));
* }</pre>
*
* @param path Path where the download should be copied.
* @since v1.8
*/

View File

@ -1582,7 +1582,7 @@ public interface ElementHandle extends JSHandle {
* href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control">control</a>, the control will be filled
* instead.
*
* <p> To send fine-grained keyboard events, use {@link ElementHandle#type ElementHandle.type()}.
* <p> To send fine-grained keyboard events, use {@link Keyboard#type Keyboard.type()}.
*
* @param value Value to set for the {@code <input>}, {@code <textarea>} or {@code [contenteditable]} element.
* @since v1.8
@ -1600,7 +1600,7 @@ public interface ElementHandle extends JSHandle {
* href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control">control</a>, the control will be filled
* instead.
*
* <p> To send fine-grained keyboard events, use {@link ElementHandle#type ElementHandle.type()}.
* <p> To send fine-grained keyboard events, use {@link Keyboard#type Keyboard.type()}.
*
* @param value Value to set for the {@code <input>}, {@code <textarea>} or {@code [contenteditable]} element.
* @since v1.8
@ -2450,24 +2450,8 @@ public interface ElementHandle extends JSHandle {
*/
String textContent();
/**
* Focuses the element, and then sends a {@code keydown}, {@code keypress}/{@code input}, and {@code keyup} event for each
* character in the text.
*
* <p> To press a special key, like {@code Control} or {@code ArrowDown}, use {@link ElementHandle#press
* ElementHandle.press()}.
*
* <p> **Usage**
* <pre>{@code
* elementHandle.type("Hello"); // Types instantly
* elementHandle.type("World", new ElementHandle.TypeOptions().setDelay(100)); // Types slower, like a user
* }</pre>
*
* <p> An example of typing into a text field and then submitting the form:
* <pre>{@code
* ElementHandle elementHandle = page.querySelector("input");
* elementHandle.type("some text");
* elementHandle.press("Enter");
* }</pre>
* @deprecated Use locator-based {@link Locator#pressSequentially Locator.pressSequentially()} instead. Read more about <a
* href="https://playwright.dev/java/docs/locators">locators</a>.
*
* @param text A text to type into a focused element.
* @since v1.8
@ -2476,24 +2460,8 @@ public interface ElementHandle extends JSHandle {
type(text, null);
}
/**
* Focuses the element, and then sends a {@code keydown}, {@code keypress}/{@code input}, and {@code keyup} event for each
* character in the text.
*
* <p> To press a special key, like {@code Control} or {@code ArrowDown}, use {@link ElementHandle#press
* ElementHandle.press()}.
*
* <p> **Usage**
* <pre>{@code
* elementHandle.type("Hello"); // Types instantly
* elementHandle.type("World", new ElementHandle.TypeOptions().setDelay(100)); // Types slower, like a user
* }</pre>
*
* <p> An example of typing into a text field and then submitting the form:
* <pre>{@code
* ElementHandle elementHandle = page.querySelector("input");
* elementHandle.type("some text");
* elementHandle.press("Enter");
* }</pre>
* @deprecated Use locator-based {@link Locator#pressSequentially Locator.pressSequentially()} instead. Read more about <a
* href="https://playwright.dev/java/docs/locators">locators</a>.
*
* @param text A text to type into a focused element.
* @since v1.8

View File

@ -4677,19 +4677,8 @@ public interface Frame {
*/
String title();
/**
* Sends a {@code keydown}, {@code keypress}/{@code input}, and {@code keyup} event for each character in the text. {@code
* frame.type} can be used to send fine-grained keyboard events. To fill values in form fields, use {@link Frame#fill
* Frame.fill()}.
*
* <p> To press a special key, like {@code Control} or {@code ArrowDown}, use {@link Keyboard#press Keyboard.press()}.
*
* <p> **Usage**
* <pre>{@code
* // Types instantly
* frame.type("#mytextarea", "Hello");
* // Types slower, like a user
* frame.type("#mytextarea", "World", new Frame.TypeOptions().setDelay(100));
* }</pre>
* @deprecated Use locator-based {@link Locator#pressSequentially Locator.pressSequentially()} instead. Read more about <a
* href="https://playwright.dev/java/docs/locators">locators</a>.
*
* @param selector A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
* @param text A text to type into a focused element.
@ -4699,19 +4688,8 @@ public interface Frame {
type(selector, text, null);
}
/**
* Sends a {@code keydown}, {@code keypress}/{@code input}, and {@code keyup} event for each character in the text. {@code
* frame.type} can be used to send fine-grained keyboard events. To fill values in form fields, use {@link Frame#fill
* Frame.fill()}.
*
* <p> To press a special key, like {@code Control} or {@code ArrowDown}, use {@link Keyboard#press Keyboard.press()}.
*
* <p> **Usage**
* <pre>{@code
* // Types instantly
* frame.type("#mytextarea", "Hello");
* // Types slower, like a user
* frame.type("#mytextarea", "World", new Frame.TypeOptions().setDelay(100));
* }</pre>
* @deprecated Use locator-based {@link Locator#pressSequentially Locator.pressSequentially()} instead. Read more about <a
* href="https://playwright.dev/java/docs/locators">locators</a>.
*
* @param selector A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
* @param text A text to type into a focused element.

View File

@ -1388,6 +1388,50 @@ public interface Locator {
return this;
}
}
class PressSequentiallyOptions {
/**
* Time to wait between key presses in milliseconds. Defaults to 0.
*/
public Double delay;
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
*/
public Boolean noWaitAfter;
/**
* Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default
* value can be changed by using the {@link BrowserContext#setDefaultTimeout BrowserContext.setDefaultTimeout()} or {@link
* Page#setDefaultTimeout Page.setDefaultTimeout()} methods.
*/
public Double timeout;
/**
* Time to wait between key presses in milliseconds. Defaults to 0.
*/
public PressSequentiallyOptions setDelay(double delay) {
this.delay = delay;
return this;
}
/**
* Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can
* opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to
* inaccessible pages. Defaults to {@code false}.
*/
public PressSequentiallyOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
return this;
}
/**
* Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default
* value can be changed by using the {@link BrowserContext#setDefaultTimeout BrowserContext.setDefaultTimeout()} or {@link
* Page#setDefaultTimeout Page.setDefaultTimeout()} methods.
*/
public PressSequentiallyOptions setTimeout(double timeout) {
this.timeout = timeout;
return this;
}
}
class ScreenshotOptions {
/**
* When set to {@code "disabled"}, stops CSS animations, CSS transitions and Web Animations. Animations get different
@ -2832,7 +2876,7 @@ public interface Locator {
* href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control">control</a>, the control will be filled
* instead.
*
* <p> To send fine-grained keyboard events, use {@link Locator#type Locator.type()}.
* <p> To send fine-grained keyboard events, use {@link Locator#pressSequentially Locator.pressSequentially()}.
*
* @param value Value to set for the {@code <input>}, {@code <textarea>} or {@code [contenteditable]} element.
* @since v1.14
@ -2859,7 +2903,7 @@ public interface Locator {
* href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control">control</a>, the control will be filled
* instead.
*
* <p> To send fine-grained keyboard events, use {@link Locator#type Locator.type()}.
* <p> To send fine-grained keyboard events, use {@link Locator#pressSequentially Locator.pressSequentially()}.
*
* @param value Value to set for the {@code <input>}, {@code <textarea>} or {@code [contenteditable]} element.
* @since v1.14
@ -3956,6 +4000,60 @@ public interface Locator {
* @since v1.14
*/
void press(String key, PressOptions options);
/**
* <strong>NOTE:</strong> In most cases, you should use {@link Locator#fill Locator.fill()} instead. You only need to press keys one by one if
* there is special keyboard handling on the page.
*
* <p> Focuses the element, and then sends a {@code keydown}, {@code keypress}/{@code input}, and {@code keyup} event for each
* character in the text.
*
* <p> To press a special key, like {@code Control} or {@code ArrowDown}, use {@link Locator#press Locator.press()}.
*
* <p> **Usage**
* <pre>{@code
* locator.pressSequentially("Hello"); // Types instantly
* locator.pressSequentially("World", new Locator.pressSequentiallyOptions().setDelay(100)); // Types slower, like a user
* }</pre>
*
* <p> An example of typing into a text field and then submitting the form:
* <pre>{@code
* Locator locator = page.getByLabel("Password");
* locator.pressSequentially("my password");
* locator.press("Enter");
* }</pre>
*
* @param text String of characters to sequentially press into a focused element.
* @since v1.38
*/
default void pressSequentially(String text) {
pressSequentially(text, null);
}
/**
* <strong>NOTE:</strong> In most cases, you should use {@link Locator#fill Locator.fill()} instead. You only need to press keys one by one if
* there is special keyboard handling on the page.
*
* <p> Focuses the element, and then sends a {@code keydown}, {@code keypress}/{@code input}, and {@code keyup} event for each
* character in the text.
*
* <p> To press a special key, like {@code Control} or {@code ArrowDown}, use {@link Locator#press Locator.press()}.
*
* <p> **Usage**
* <pre>{@code
* locator.pressSequentially("Hello"); // Types instantly
* locator.pressSequentially("World", new Locator.pressSequentiallyOptions().setDelay(100)); // Types slower, like a user
* }</pre>
*
* <p> An example of typing into a text field and then submitting the form:
* <pre>{@code
* Locator locator = page.getByLabel("Password");
* locator.pressSequentially("my password");
* locator.press("Enter");
* }</pre>
*
* @param text String of characters to sequentially press into a focused element.
* @since v1.38
*/
void pressSequentially(String text, PressSequentiallyOptions options);
/**
* Take a screenshot of the element matching the locator.
*
@ -4865,26 +4963,9 @@ public interface Locator {
*/
String textContent(TextContentOptions options);
/**
* <strong>NOTE:</strong> In most cases, you should use {@link Locator#fill Locator.fill()} instead. You only need to type characters if there is
* special keyboard handling on the page.
*
* <p> Focuses the element, and then sends a {@code keydown}, {@code keypress}/{@code input}, and {@code keyup} event for each
* character in the text.
*
* <p> To press a special key, like {@code Control} or {@code ArrowDown}, use {@link Locator#press Locator.press()}.
*
* <p> **Usage**
* <pre>{@code
* element.type("Hello"); // Types instantly
* element.type("World", new Locator.TypeOptions().setDelay(100)); // Types slower, like a user
* }</pre>
*
* <p> An example of typing into a text field and then submitting the form:
* <pre>{@code
* Locator element = page.getByLabel("Password");
* element.type("my password");
* element.press("Enter");
* }</pre>
* @deprecated In most cases, you should use {@link Locator#fill Locator.fill()} instead. You only need to press keys one by one if
* there is special keyboard handling on the page - in this case use {@link Locator#pressSequentially
* Locator.pressSequentially()}.
*
* @param text A text to type into a focused element.
* @since v1.14
@ -4893,26 +4974,9 @@ public interface Locator {
type(text, null);
}
/**
* <strong>NOTE:</strong> In most cases, you should use {@link Locator#fill Locator.fill()} instead. You only need to type characters if there is
* special keyboard handling on the page.
*
* <p> Focuses the element, and then sends a {@code keydown}, {@code keypress}/{@code input}, and {@code keyup} event for each
* character in the text.
*
* <p> To press a special key, like {@code Control} or {@code ArrowDown}, use {@link Locator#press Locator.press()}.
*
* <p> **Usage**
* <pre>{@code
* element.type("Hello"); // Types instantly
* element.type("World", new Locator.TypeOptions().setDelay(100)); // Types slower, like a user
* }</pre>
*
* <p> An example of typing into a text field and then submitting the form:
* <pre>{@code
* Locator element = page.getByLabel("Password");
* element.type("my password");
* element.press("Enter");
* }</pre>
* @deprecated In most cases, you should use {@link Locator#fill Locator.fill()} instead. You only need to press keys one by one if
* there is special keyboard handling on the page - in this case use {@link Locator#pressSequentially
* Locator.pressSequentially()}.
*
* @param text A text to type into a focused element.
* @since v1.14

View File

@ -6942,19 +6942,8 @@ public interface Page extends AutoCloseable {
*/
Touchscreen touchscreen();
/**
* Sends a {@code keydown}, {@code keypress}/{@code input}, and {@code keyup} event for each character in the text. {@code
* page.type} can be used to send fine-grained keyboard events. To fill values in form fields, use {@link Page#fill
* Page.fill()}.
*
* <p> To press a special key, like {@code Control} or {@code ArrowDown}, use {@link Keyboard#press Keyboard.press()}.
*
* <p> **Usage**
* <pre>{@code
* // Types instantly
* page.type("#mytextarea", "Hello");
* // Types slower, like a user
* page.type("#mytextarea", "World", new Page.TypeOptions().setDelay(100));
* }</pre>
* @deprecated Use locator-based {@link Locator#pressSequentially Locator.pressSequentially()} instead. Read more about <a
* href="https://playwright.dev/java/docs/locators">locators</a>.
*
* @param selector A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
* @param text A text to type into a focused element.
@ -6964,19 +6953,8 @@ public interface Page extends AutoCloseable {
type(selector, text, null);
}
/**
* Sends a {@code keydown}, {@code keypress}/{@code input}, and {@code keyup} event for each character in the text. {@code
* page.type} can be used to send fine-grained keyboard events. To fill values in form fields, use {@link Page#fill
* Page.fill()}.
*
* <p> To press a special key, like {@code Control} or {@code ArrowDown}, use {@link Keyboard#press Keyboard.press()}.
*
* <p> **Usage**
* <pre>{@code
* // Types instantly
* page.type("#mytextarea", "Hello");
* // Types slower, like a user
* page.type("#mytextarea", "World", new Page.TypeOptions().setDelay(100));
* }</pre>
* @deprecated Use locator-based {@link Locator#pressSequentially Locator.pressSequentially()} instead. Read more about <a
* href="https://playwright.dev/java/docs/locators">locators</a>.
*
* @param selector A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
* @param text A text to type into a focused element.

View File

@ -0,0 +1,47 @@
/*
* 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;
/**
* {@code PageError} class represents objects created by context when there are unhandled execeptions thrown on the pages
* and dispatched via the {@link BrowserContext#onPageError BrowserContext.onPageError()} event.
* <pre>{@code
* // Log all uncaught errors to the terminal
* context.onPageError(pagerror -> {
* System.out.println("Uncaught exception: " + pagerror.error());
* });
*
* // Navigate to a page with an exception.
* page.navigate("data:text/html,<script>throw new Error('Test')</script>");
* }</pre>
*/
public interface PageError {
/**
* The page that produced this unhandled exception, if any.
*
* @since v1.38
*/
Page page();
/**
* Unhandled error that was thrown.
*
* @since v1.38
*/
String error();
}

View File

@ -62,6 +62,22 @@ public interface Request {
/**
* Returns the {@code Frame} that initiated this request.
*
* <p> **Usage**
* <pre>{@code
* String frameUrl = request.frame().url();
* }</pre>
*
* <p> **Details**
*
* <p> Note that in some cases the frame is not available, and this method will throw.
* <ul>
* <li> When request originates in the Service Worker. You can use {@code request.serviceWorker()} to check that.</li>
* <li> When navigation request is issued before the corresponding frame is created. You can use {@link
* Request#isNavigationRequest Request.isNavigationRequest()} to check that.</li>
* </ul>
*
* <p> Here is an example that handles all the cases:
*
* @since v1.8
*/
Frame frame();
@ -91,6 +107,9 @@ public interface Request {
/**
* Whether this request is driving frame's navigation.
*
* <p> Some navigation requests are issued before the corresponding frame is created, and therefore do not have {@link
* Request#frame Request.frame()} available.
*
* @since v1.8
*/
boolean isNavigationRequest();

View File

@ -82,6 +82,7 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
CONSOLE,
DIALOG,
PAGE,
PAGEERROR,
REQUEST,
REQUESTFAILED,
REQUESTFINISHED,
@ -154,6 +155,16 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
listeners.remove(EventType.PAGE, handler);
}
@Override
public void onPageError(Consumer<PageError> handler) {
listeners.add(EventType.PAGEERROR, handler);
}
@Override
public void offPageError(Consumer<PageError> handler) {
listeners.remove(EventType.PAGEERROR, handler);
}
@Override
public void onRequest(Consumer<Request> handler) {
listeners.add(EventType.REQUEST, handler);
@ -645,6 +656,7 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
}
} else if ("route".equals(event)) {
RouteImpl route = connection.getExistingObject(params.getAsJsonObject("route").get("guid").getAsString());
route.browserContext = this;
handleRoute(route);
} else if ("page".equals(event)) {
PageImpl page = connection.getExistingObject(params.getAsJsonObject("page").get("guid").getAsString());
@ -710,6 +722,25 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
PageImpl page = connection.getExistingObject(params.getAsJsonObject("page").get("guid").getAsString());
page.listeners.notify(PageImpl.EventType.RESPONSE, response);
}
} else if ("pageError".equals(event)) {
SerializedError error = gson().fromJson(params.getAsJsonObject("error"), SerializedError.class);
String errorStr = "";
if (error.error != null) {
errorStr = error.error.name + ": " + error.error.message;
if (error.error.stack != null && !error.error.stack.isEmpty()) {
errorStr += "\n" + error.error.stack;
}
}
PageImpl page;
try {
page = connection.getExistingObject(params.getAsJsonObject("page").get("guid").getAsString());
} catch (PlaywrightException e) {
page = null;
}
listeners.notify(BrowserContextImpl.EventType.PAGEERROR, new PageErrorImpl(page, errorStr));
if (page != null) {
page.listeners.notify(PageImpl.EventType.PAGEERROR, errorStr);
}
} else if ("close".equals(event)) {
didClose();
}

View File

@ -203,6 +203,10 @@ class BrowserImpl extends ChannelOwner implements Browser {
params.addProperty("noDefaultViewport", true);
}
}
params.remove("acceptDownloads");
if (options.acceptDownloads != null) {
params.addProperty("acceptDownloads", options.acceptDownloads ? "accept" : "deny");
}
JsonElement result = sendMessage("newContext", params);
BrowserContextImpl context = connection.getExistingObject(result.getAsJsonObject().getAsJsonObject("context").get("guid").getAsString());
context.videosDir = options.recordVideoDir;

View File

@ -223,6 +223,10 @@ class BrowserTypeImpl extends ChannelOwner implements BrowserType {
params.addProperty("noDefaultViewport", true);
}
}
params.remove("acceptDownloads");
if (options.acceptDownloads != null) {
params.addProperty("acceptDownloads", options.acceptDownloads ? "accept" : "deny");
}
JsonObject json = sendMessage("launchPersistentContext", params).getAsJsonObject();
BrowserContextImpl context = connection.getExistingObject(json.getAsJsonObject("context").get("guid").getAsString());
context.videosDir = options.recordVideoDir;

View File

@ -436,6 +436,11 @@ class LocatorImpl implements Locator {
frame.press(selector, key, convertType(options, Frame.PressOptions.class).setStrict(true));
}
@Override
public void pressSequentially(String text, PressSequentiallyOptions options) {
type(text, convertType(options, TypeOptions.class));
}
@Override
public byte[] screenshot(ScreenshotOptions options) {
return withElement((h, o) -> h.screenshot(o), convertType(options, ElementHandle.ScreenshotOptions.class));

View File

@ -0,0 +1,23 @@
package com.microsoft.playwright.impl;
import com.microsoft.playwright.PageError;
public class PageErrorImpl implements PageError {
private final PageImpl page;
private final String error;
PageErrorImpl(PageImpl page, String error) {
this.page = page;
this.error = error;
}
@Override
public PageImpl page() {
return page;
}
@Override
public String error() {
return error;
}
}

View File

@ -171,6 +171,7 @@ public class PageImpl extends ChannelOwner implements Page {
listeners.notify(EventType.FRAMEDETACHED, frame);
} else if ("route".equals(event)) {
RouteImpl route = connection.getExistingObject(params.getAsJsonObject("route").get("guid").getAsString());
route.browserContext = browserContext;
Router.HandleResult handled = routes.handle(route);
if (handled != Router.HandleResult.NoMatchingHandler) {
updateInterceptionPatterns();
@ -182,16 +183,6 @@ public class PageImpl extends ChannelOwner implements Page {
String artifactGuid = params.getAsJsonObject("artifact").get("guid").getAsString();
ArtifactImpl artifact = connection.getExistingObject(artifactGuid);
forceVideo().setArtifact(artifact);
} else if ("pageError".equals(event)) {
SerializedError error = gson().fromJson(params.getAsJsonObject("error"), SerializedError.class);
String errorStr = "";
if (error.error != null) {
errorStr = error.error.name + ": " + error.error.message;
if (error.error.stack != null && !error.error.stack.isEmpty()) {
errorStr += "\n" + error.error.stack;
}
}
listeners.notify(EventType.PAGEERROR, errorStr);
} else if ("crash".equals(event)) {
listeners.notify(EventType.CRASH, this);
} else if ("close".equals(event)) {

View File

@ -78,7 +78,13 @@ public class RequestImpl extends ChannelOwner implements Request {
@Override
public FrameImpl frame() {
return connection.getExistingObject(initializer.getAsJsonObject("frame").get("guid").getAsString());
FrameImpl frame = connection.getExistingObject(initializer.getAsJsonObject("frame").get("guid").getAsString());
if (frame.page == null) {
throw new PlaywrightException("Frame for this navigation request is not available, because the request\n" +
"was issued before the frame is created. You can check whether the request\n" +
"is a navigation request by calling isNavigationRequest() method.");
}
return frame;
}
@Override

View File

@ -32,7 +32,7 @@ import static com.microsoft.playwright.impl.Utils.convertType;
public class RouteImpl extends ChannelOwner implements Route {
private final RequestImpl request;
private boolean handled;
BrowserContextImpl browserContext;
boolean fallbackCalled;
boolean shouldResumeIfFallbackIsCalled;
@ -99,7 +99,7 @@ public class RouteImpl extends ChannelOwner implements Route {
if (fetchOptions != null && fetchOptions.timeout != null) {
options.timeout = fetchOptions.timeout;
}
APIRequestContextImpl apiRequest = request.frame().page().context().request();
APIRequestContextImpl apiRequest = browserContext.request();
String url = (fetchOptions == null || fetchOptions.url == null) ? request().url() : fetchOptions.url;
return apiRequest.fetch(url, options);
}

View File

@ -20,10 +20,17 @@ import org.junit.jupiter.api.*;
import com.microsoft.playwright.options.SameSiteAttribute;
import javax.sql.rowset.Predicate;
import java.io.IOException;
import java.security.Provider;
import java.time.Duration;
import java.time.Instant;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
import static com.microsoft.playwright.Utils.getBrowserNameFromEnv;
import static com.microsoft.playwright.Utils.nextFreePort;
import static org.junit.jupiter.api.Assertions.assertTrue;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class TestBase {
@ -150,6 +157,13 @@ public class TestBase {
}
}
void waitForCondition(BooleanSupplier predicate) {
waitForCondition(predicate, 5_000);
}
void waitForCondition(BooleanSupplier predicate, int timeoutMs) {
page.waitForCondition(predicate, new Page.WaitForConditionOptions().setTimeout(timeoutMs));
}
private static SameSiteAttribute initSameSiteAttribute() {
if (isChromium()) return SameSiteAttribute.LAX;
if (isWebKit()) return SameSiteAttribute.NONE;

View File

@ -7,6 +7,7 @@ import java.io.OutputStreamWriter;
import java.io.Writer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TestBrowserContextEvents extends TestBase {
@Test
@ -156,4 +157,17 @@ public class TestBrowserContextEvents extends TestBase {
page.waitForCondition(() -> "hello".equals(popup.evaluate("window.result")),
new Page.WaitForConditionOptions().setTimeout(5_000));
}
@Test
void pageErrorEventShouldWork() {
PageError[] pageerror = { null };
context.onPageError(e -> {
pageerror[0] = e;
});
page.setContent("<script>throw new Error('boom')</script>");
waitForCondition(() -> pageerror[0] != null);
assertEquals(page, pageerror[0].page());
assertTrue(pageerror[0].error().contains("boom"), pageerror[0].error());
}
}

View File

@ -116,4 +116,11 @@ public class TestLocatorMisc extends TestBase{
assertEquals("outer", divLocator.locator("input").inputValue());
assertEquals("inner", page.frameLocator("iframe").locator(divLocator).locator("input").inputValue());
}
@Test
void shouldPressSequentially() {
page.setContent("<input type='text' />");
page.locator("input").pressSequentially("hello");
assertEquals("hello", page.evalOnSelector("input", "input => input.value"));
}
}

View File

@ -66,17 +66,18 @@ public class TestPageEventNetwork extends TestBase {
assertTrue(failedRequests.get(0).url().contains("one-style.css"));
assertNull(failedRequests.get(0).response());
assertEquals("stylesheet", failedRequests.get(0).resourceType());
String error = failedRequests.get(0).failure();
if (isChromium()) {
assertEquals("net::ERR_EMPTY_RESPONSE", failedRequests.get(0).failure());
assertEquals("net::ERR_EMPTY_RESPONSE", error);
} else if (isWebKit()) {
if (isMac)
assertEquals("The network connection was lost.", failedRequests.get(0).failure());
assertEquals("The network connection was lost.", error);
else if (isWindows)
assertEquals("Server returned nothing (no headers, no data)", failedRequests.get(0).failure());
assertEquals("Server returned nothing (no headers, no data)", error);
else
assertEquals("Message Corrupt", failedRequests.get(0).failure());
assertTrue("Message Corrupt".equals(error) || "Connection terminated unexpectedly".equals(error), error);
} else {
assertEquals("NS_ERROR_NET_RESET", failedRequests.get(0).failure());
assertEquals("NS_ERROR_NET_RESET", error);
}
assertNotNull(failedRequests.get(0).frame());
}

View File

@ -0,0 +1,17 @@
package com.microsoft.playwright;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestPageEventPopup extends TestBase {
@Test
void shouldWorkWithClickingTarget_blank() {
page.navigate(server.EMPTY_PAGE);
page.setContent("<a target=_blank rel='opener' href='/one-style.html'>yo</a>");
Page popup = page.waitForPopup(() -> page.click("a"));
assertEquals(false, page.evaluate("() => !!window.opener"));
assertEquals(true, popup.evaluate("() => !!window.opener"));
assertEquals(popup, popup.mainFrame().page());
}
}

View File

@ -21,6 +21,8 @@ import com.microsoft.playwright.options.HttpHeader;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@ -113,4 +115,24 @@ public class TestPageNetworkRequest extends TestBase {
assertEquals("POST", request.method());
assertEquals(403, request.response().status());
}
@Test
void shouldNotAllowToAccessFrameOnPopupMainRequest() {
page.setContent("<a target=_blank href='" + server.EMPTY_PAGE + "'>click me</a>");
Request[] request = { null };
PlaywrightException[] error = { null };
page.context().onRequest(req -> {
request[0] = req;
try {
req.frame();
} catch (PlaywrightException e) {
error[0] = e;
}
});
page.getByText("click me").click();
waitForCondition(() -> request[0] != null);
assertTrue(request[0].isNavigationRequest());
assertTrue(error[0].getMessage().contains("Frame for this navigation request is not available"), error[0].getMessage());
}
}

View File

@ -0,0 +1,18 @@
package com.microsoft.playwright;
import org.junit.jupiter.api.Test;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
public class TestPageRequestIntercept extends TestBase {
@Test
void shouldFulfillPopupMainRequestUsingAlias() {
page.context().route("**/*", route -> {
APIResponse response = route.fetch();
route.fulfill(new Route.FulfillOptions().setResponse(response).setBody("hello" ));
});
page.setContent("<a target=_blank href='" + server.EMPTY_PAGE + "'>click me</a>");
Page popup = page.waitForPopup(() -> page.getByText("click me").click());
assertThat(popup.locator("body")).hasText("hello");
}
}

View File

@ -1 +1 @@
1.37.0-beta-1691701681000
1.38.0-alpha-1692826278000

View File

@ -1156,13 +1156,18 @@ public class ApiGenerator {
File assertionsDir = new File(cwd,"playwright/src/main/java/com/microsoft/playwright/assertions");
System.out.println("Writing assertion files to: " + dir.getCanonicalPath());
generate(api, assertionsDir, "com.microsoft.playwright.assertions", isAssertion());
generate(api, assertionsDir, "com.microsoft.playwright.assertions", isAssertion().and(isSoftAssertion().negate()));
}
private static Predicate<String> isAssertion() {
return className -> className.toLowerCase().contains("assert");
}
// TODO: Remove this predicate once SoftAssertions are implemented.
private static Predicate<String> isSoftAssertion() {
return className -> className.contains("SoftAssertions");
}
private void generate(JsonArray api, File dir, String packageName, Predicate<String> classFilter) throws IOException {
Map<String, TypeDefinition> topLevelTypes = new HashMap<>();
for (JsonElement entry: api) {