docs: remove Promise.all from examples (#19154)

Replaced with explicit `popupPromise` variable.
This commit is contained in:
Dmitry Gozman 2022-11-30 12:36:35 -08:00 committed by GitHub
parent f952e1147b
commit 499324961a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 277 additions and 397 deletions

View file

@ -106,30 +106,29 @@ popup with `window.open('http://example.com')`, this event will fire when the ne
done and its response has started loading in the popup. done and its response has started loading in the popup.
```js ```js
const [newPage] = await Promise.all([ const newPagePromise = context.waitForEvent('page');
context.waitForEvent('page'), await page.getByText('open new page').click();
page.locator('a[target=_blank]').click(), const newPage = await newPagePromise;
]);
console.log(await newPage.evaluate('location.href')); console.log(await newPage.evaluate('location.href'));
``` ```
```java ```java
Page newPage = context.waitForPage(() -> { Page newPage = context.waitForPage(() -> {
page.locator("a[target=_blank]").click(); page.getByText("open new page").click();
}); });
System.out.println(newPage.evaluate("location.href")); System.out.println(newPage.evaluate("location.href"));
``` ```
```python async ```python async
async with context.expect_page() as page_info: async with context.expect_page() as page_info:
await page.locator("a[target=_blank]").click(), await page.get_by_text("open new page").click(),
page = await page_info.value page = await page_info.value
print(await page.evaluate("location.href")) print(await page.evaluate("location.href"))
``` ```
```python sync ```python sync
with context.expect_page() as page_info: with context.expect_page() as page_info:
page.locator("a[target=_blank]").click(), page.get_by_text("open new page").click(),
page = page_info.value page = page_info.value
print(page.evaluate("location.href")) print(page.evaluate("location.href"))
``` ```
@ -137,7 +136,7 @@ print(page.evaluate("location.href"))
```csharp ```csharp
var popup = await context.RunAndWaitForPageAsync(async => var popup = await context.RunAndWaitForPageAsync(async =>
{ {
await page.Locator("a").ClickAsync(); await page.GetByText("open new page").ClickAsync();
}); });
Console.WriteLine(await popup.EvaluateAsync<string>("location.href")); Console.WriteLine(await popup.EvaluateAsync<string>("location.href"));
``` ```
@ -1311,14 +1310,13 @@ value. Will throw an error if the context closes before the event is fired. Retu
**Usage** **Usage**
```js ```js
const [page, _] = await Promise.all([ const pagePromise = context.waitForEvent('page');
context.waitForEvent('page'), await page.getByRole('button').click();
page.getByRole('button').click() const page = await pagePromise;
]);
``` ```
```java ```java
Page newPage = context.waitForPage(() -> page.getByRole("button").click()); Page newPage = context.waitForPage(() -> page.getByRole(AriaRole.BUTTON).click());
``` ```
```python async ```python async
@ -1336,7 +1334,7 @@ page = event_info.value
```csharp ```csharp
var page = await context.RunAndWaitForPageAsync(async () => var page = await context.RunAndWaitForPageAsync(async () =>
{ {
await page.GetByRole("button").ClickAsync(); await page.GetByRole(AriaRole.Button).ClickAsync();
}); });
``` ```

View file

@ -16,13 +16,11 @@ page.on('console', msg => {
}); });
// Get the next console log // Get the next console log
const [msg] = await Promise.all([ const msgPromise = page.waitForEvent('console');
page.waitForEvent('console'), await page.evaluate(() => {
// Issue console.log inside the page console.log('hello', 42, { foo: 'bar' }); // Issue console.log inside the page
page.evaluate(() => { });
console.log('hello', 42, { foo: 'bar' }); const msg = await msgPromise;
}),
]);
// Deconstruct console log arguments // Deconstruct console log arguments
await msg.args[0].jsonValue() // hello await msg.args[0].jsonValue() // hello

View file

@ -9,16 +9,13 @@ browser context is closed.
Download event is emitted once the download starts. Download path becomes available once download completes: Download event is emitted once the download starts. Download path becomes available once download completes:
```js ```js
// Note that Promise.all prevents a race condition // Start waiting for download before clicking. Note no await.
// between clicking and waiting for the download. const downloadPromise = page.waitForEvent('download');
const [ download ] = await Promise.all([ await page.getByText('Download file').click();
// It is important to call waitForEvent before click to set up waiting. const download = await downloadPromise;
page.waitForEvent('download'),
// Triggers the download. // Wait for the download process to complete.
page.getByText('Download file').click(), console.log(await download.path());
]);
// wait for download to complete
const path = await download.path();
``` ```
```java ```java

View file

@ -144,10 +144,9 @@ Waits for event to fire and passes its value into the predicate function. Return
**Usage** **Usage**
```js ```js
const [window] = await Promise.all([ const windowPromise = electronApp.waitForEvent('window');
electronApp.waitForEvent('window'), await mainWindow.click('button');
mainWindow.click('button') const window = await windowPromise;
]);
``` ```
### param: ElectronApplication.waitForEvent.event = %%-wait-for-event-event-%% ### param: ElectronApplication.waitForEvent.event = %%-wait-for-event-event-%%

View file

@ -4,32 +4,28 @@
[FileChooser] objects are dispatched by the page in the [`event: Page.fileChooser`] event. [FileChooser] objects are dispatched by the page in the [`event: Page.fileChooser`] event.
```js ```js
// Note that Promise.all prevents a race condition // Start waiting for file chooser before clicking. Note no await.
// between clicking and waiting for the file chooser. const fileChooserPromise = page.waitForEvent('filechooser');
const [fileChooser] = await Promise.all([ await page.getByText('Upload file').click();
// It is important to call waitForEvent before click to set up waiting. const fileChooser = await fileChooserPromise;
page.waitForEvent('filechooser'),
// Opens the file chooser.
page.getByText('Upload').click(),
]);
await fileChooser.setFiles('myfile.pdf'); await fileChooser.setFiles('myfile.pdf');
``` ```
```java ```java
FileChooser fileChooser = page.waitForFileChooser(() -> page.getByText("Upload").click()); FileChooser fileChooser = page.waitForFileChooser(() -> page.getByText("Upload file").click());
fileChooser.setFiles(Paths.get("myfile.pdf")); fileChooser.setFiles(Paths.get("myfile.pdf"));
``` ```
```python async ```python async
async with page.expect_file_chooser() as fc_info: async with page.expect_file_chooser() as fc_info:
await page.get_by_text("Upload").click() await page.get_by_text("Upload file").click()
file_chooser = await fc_info.value file_chooser = await fc_info.value
await file_chooser.set_files("myfile.pdf") await file_chooser.set_files("myfile.pdf")
``` ```
```python sync ```python sync
with page.expect_file_chooser() as fc_info: with page.expect_file_chooser() as fc_info:
page.get_by_text("Upload").click() page.get_by_text("Upload file").click()
file_chooser = fc_info.value file_chooser = fc_info.value
file_chooser.set_files("myfile.pdf") file_chooser.set_files("myfile.pdf")
``` ```
@ -37,7 +33,7 @@ file_chooser.set_files("myfile.pdf")
```csharp ```csharp
var fileChooser = await page.RunAndWaitForFileChooserAsync(async () => var fileChooser = await page.RunAndWaitForFileChooserAsync(async () =>
{ {
await page.GetByText("Upload").ClickAsync(); await page.GetByText("Upload file").ClickAsync();
}); });
await fileChooser.SetFilesAsync("temp.txt"); await fileChooser.SetFilesAsync("temp.txt");
``` ```

View file

@ -1928,15 +1928,15 @@ This method waits for the frame to navigate to a new URL. It is useful for when
the frame to navigate. Consider this example: the frame to navigate. Consider this example:
```js ```js
const [response] = await Promise.all([ // Start waiting for navigation before clicking. Note no await.
frame.waitForNavigation(), // The promise resolves after navigation has finished const navigationPromise = page.waitForNavigation();
frame.click('a.delayed-navigation'), // Clicking the link will indirectly cause a navigation await page.getByText('Navigate after timeout').click();
]); await navigationPromise;
``` ```
```java ```java
// The method returns after navigation has finished // The method returns after navigation has finished
Response response = frame.waitForNavigation(() -> { frame.waitForNavigation(() -> {
// Clicking the link will indirectly cause a navigation // Clicking the link will indirectly cause a navigation
frame.click("a.delayed-navigation"); frame.click("a.delayed-navigation");
}); });

View file

@ -448,34 +448,30 @@ popup with `window.open('http://example.com')`, this event will fire when the ne
done and its response has started loading in the popup. done and its response has started loading in the popup.
```js ```js
// Note that Promise.all prevents a race condition // Start waiting for popup before clicking. Note no await.
// between evaluating and waiting for the popup. const popupPromise = page.waitForEvent('popup');
const [popup] = await Promise.all([ await page.getByText('open the popup').click();
// It is important to call waitForEvent first. const popup = await popupPromise;
page.waitForEvent('popup'),
// Opens the popup.
page.evaluate(() => window.open('https://example.com')),
]);
console.log(await popup.evaluate('location.href')); console.log(await popup.evaluate('location.href'));
``` ```
```java ```java
Page popup = page.waitForPopup(() -> { Page popup = page.waitForPopup(() -> {
page.evaluate("() => window.open('https://example.com')"); page.getByText("open the popup").click();
}); });
System.out.println(popup.evaluate("location.href")); System.out.println(popup.evaluate("location.href"));
``` ```
```python async ```python async
async with page.expect_event("popup") as page_info: async with page.expect_event("popup") as page_info:
page.evaluate("window.open('https://example.com')") await page.get_by_text("open the popup").click()
popup = await page_info.value popup = await page_info.value
print(await popup.evaluate("location.href")) print(await popup.evaluate("location.href"))
``` ```
```python sync ```python sync
with page.expect_event("popup") as page_info: with page.expect_event("popup") as page_info:
page.evaluate("window.open('https://example.com')") page.get_by_text("open the popup").click()
popup = page_info.value popup = page_info.value
print(popup.evaluate("location.href")) print(popup.evaluate("location.href"))
``` ```
@ -483,7 +479,7 @@ print(popup.evaluate("location.href"))
```csharp ```csharp
var popup = await page.RunAndWaitForPopupAsync(async () => var popup = await page.RunAndWaitForPopupAsync(async () =>
{ {
await page.EvaluateAsync("() => window.open('https://microsoft.com')"); await page.GetByText("open the popup").ClickAsync();
}); });
Console.WriteLine(await popup.EvaluateAsync<string>("location.href")); Console.WriteLine(await popup.EvaluateAsync<string>("location.href"));
``` ```
@ -3761,14 +3757,10 @@ value. Will throw an error if the page is closed before the event is fired. Retu
**Usage** **Usage**
```js ```js
// Note that Promise.all prevents a race condition // Start waiting for download before clicking. Note no await.
// between clicking and waiting for the event. const downloadPromise = page.waitForEvent('download');
const [frame, _] = await Promise.all([ await page.getByText('Download file').click();
// It is important to call waitForEvent before click to set up waiting. const download = await downloadPromise;
page.waitForEvent('framenavigated'),
// Triggers the navigation.
page.getByRole('button').click(),
]);
``` ```
```python async ```python async
@ -3987,20 +3979,18 @@ await page.WaitForLoadStateAsync(); // The promise resolves after 'load' event.
``` ```
```js ```js
const [popup] = await Promise.all([ const popupPromise = page.waitForEvent('popup');
// It is important to call waitForEvent before click to set up waiting. await page.getByRole('button').click(); // Click triggers a popup.
page.waitForEvent('popup'), const popup = await popupPromise;
// Click triggers a popup. await popup.waitForLoadState('domcontentloaded'); // Wait for the 'DOMContentLoaded' event.
page.getByRole('button').click(),
])
await popup.waitForLoadState('domcontentloaded'); // The promise resolves after 'domcontentloaded' event.
console.log(await popup.title()); // Popup is ready to use. console.log(await popup.title()); // Popup is ready to use.
``` ```
```java ```java
Page popup = page.waitForPopup(() -> { Page popup = page.waitForPopup(() -> {
page.getByRole("button").click(); // Click triggers a popup. page.getByRole(AriaRole.BUTTON).click(); // Click triggers a popup.
}); });
// Wait for the "DOMContentLoaded" event
popup.waitForLoadState(LoadState.DOMCONTENTLOADED); popup.waitForLoadState(LoadState.DOMCONTENTLOADED);
System.out.println(popup.title()); // Popup is ready to use. System.out.println(popup.title()); // Popup is ready to use.
``` ```
@ -4009,7 +3999,7 @@ System.out.println(popup.title()); // Popup is ready to use.
async with page.expect_popup() as page_info: async with page.expect_popup() as page_info:
await page.get_by_role("button").click() # click triggers a popup. await page.get_by_role("button").click() # click triggers a popup.
popup = await page_info.value popup = await page_info.value
# Following resolves after "domcontentloaded" event. # Wait for the "DOMContentLoaded" event.
await popup.wait_for_load_state("domcontentloaded") await popup.wait_for_load_state("domcontentloaded")
print(await popup.title()) # popup is ready to use. print(await popup.title()) # popup is ready to use.
``` ```
@ -4018,7 +4008,7 @@ print(await popup.title()) # popup is ready to use.
with page.expect_popup() as page_info: with page.expect_popup() as page_info:
page.get_by_role("button").click() # click triggers a popup. page.get_by_role("button").click() # click triggers a popup.
popup = page_info.value popup = page_info.value
# Following resolves after "domcontentloaded" event. # Wait for the "DOMContentLoaded" event.
popup.wait_for_load_state("domcontentloaded") popup.wait_for_load_state("domcontentloaded")
print(popup.title()) # popup is ready to use. print(popup.title()) # popup is ready to use.
``` ```
@ -4026,8 +4016,9 @@ print(popup.title()) # popup is ready to use.
```csharp ```csharp
var popup = await page.RunAndWaitForPopupAsync(async () => var popup = await page.RunAndWaitForPopupAsync(async () =>
{ {
await page.GetByRole("button").ClickAsync(); // click triggers the popup/ await page.GetByRole(AriaRole.Button).ClickAsync(); // click triggers the popup
}); });
// Wait for the "DOMContentLoaded" event.
await popup.WaitForLoadStateAsync(LoadState.DOMContentLoaded); await popup.WaitForLoadStateAsync(LoadState.DOMContentLoaded);
Console.WriteLine(await popup.TitleAsync()); // popup is ready to use. Console.WriteLine(await popup.TitleAsync()); // popup is ready to use.
``` ```
@ -4056,40 +4047,39 @@ cause the page to navigate. e.g. The click target has an `onclick` handler that
Consider this example: Consider this example:
```js ```js
// Note that Promise.all prevents a race condition // Start waiting for navigation before clicking. Note no await.
// between clicking and waiting for the navigation. const navigationPromise = page.waitForNavigation();
const [response] = await Promise.all([ await page.getByText('Navigate after timeout').click();
// It is important to call waitForNavigation before click to set up waiting. await navigationPromise;
page.waitForNavigation(),
// Clicking the link will indirectly cause a navigation.
page.locator('a.delayed-navigation').click(),
]);
``` ```
```java ```java
// The method returns after navigation has finished // The method returns after navigation has finished
Response response = page.waitForNavigation(() -> { Response response = page.waitForNavigation(() -> {
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation // This action triggers the navigation after a timeout.
page.getByText("Navigate after timeout").click();
}); });
``` ```
```python async ```python async
async with page.expect_navigation(): async with page.expect_navigation():
await page.click("a.delayed-navigation") # clicking the link will indirectly cause a navigation # This action triggers the navigation after a timeout.
await page.get_by_text("Navigate after timeout").click()
# Resolves after navigation has finished # Resolves after navigation has finished
``` ```
```python sync ```python sync
with page.expect_navigation(): with page.expect_navigation():
page.click("a.delayed-navigation") # clicking the link will indirectly cause a navigation # This action triggers the navigation after a timeout.
page.get_by_text("Navigate after timeout").click()
# Resolves after navigation has finished # Resolves after navigation has finished
``` ```
```csharp ```csharp
await page.RunAndWaitForNavigationAsync(async () => await page.RunAndWaitForNavigationAsync(async () =>
{ {
// Clicking the link will indirectly cause a navigation. // This action triggers the navigation after a timeout.
await page.ClickAsync("a.delayed-navigation"); await page.GetByText("Navigate after timeout").ClickAsync();
}); });
// The method continues after navigation has finished // The method continues after navigation has finished
@ -4141,57 +4131,50 @@ Waits for the matching request and returns it. See [waiting for event](../events
**Usage** **Usage**
```js ```js
// Note that Promise.all prevents a race condition // Start waiting for request before clicking. Note no await.
// between clicking and waiting for the request. const requestPromise = page.waitForRequest('https://example.com/resource');
const [request] = await Promise.all([ await page.getByText('trigger request').click();
// Waits for the next request with the specified url const request = await requestPromise;
page.waitForRequest('https://example.com/resource'),
// Triggers the request
page.click('button.triggers-request'),
]);
// Alternative way with a predicate. // Alternative way with a predicate. Note no await.
const [request] = await Promise.all([ const requestPromise = page.waitForRequest(request => request.url() === 'https://example.com' && request.method() === 'GET');
// Waits for the next request matching some conditions await page.getByText('trigger request').click();
page.waitForRequest(request => request.url() === 'https://example.com' && request.method() === 'GET'), const request = await requestPromise;
// Triggers the request
page.click('button.triggers-request'),
]);
``` ```
```java ```java
// Waits for the next request with the specified url // Waits for the next request with the specified url
Request request = page.waitForRequest("https://example.com/resource", () -> { Request request = page.waitForRequest("https://example.com/resource", () -> {
// Triggers the request // Triggers the request
page.click("button.triggers-request"); page.getByText("trigger request").click();
}); });
// Waits for the next request matching some conditions // Waits for the next request matching some conditions
Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> { Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> {
// Triggers the request // Triggers the request
page.click("button.triggers-request"); page.getByText("trigger request").click();
}); });
``` ```
```python async ```python async
async with page.expect_request("http://example.com/resource") as first: async with page.expect_request("http://example.com/resource") as first:
await page.click('button') await page.get_by_text("trigger request").click()
first_request = await first.value first_request = await first.value
# or with a lambda # or with a lambda
async with page.expect_request(lambda request: request.url == "http://example.com" and request.method == "get") as second: async with page.expect_request(lambda request: request.url == "http://example.com" and request.method == "get") as second:
await page.click('img') await page.get_by_text("trigger request").click()
second_request = await second.value second_request = await second.value
``` ```
```python sync ```python sync
with page.expect_request("http://example.com/resource") as first: with page.expect_request("http://example.com/resource") as first:
page.click('button') page.get_by_text("trigger request").click()
first_request = first.value first_request = first.value
# or with a lambda # or with a lambda
with page.expect_request(lambda request: request.url == "http://example.com" and request.method == "get") as second: with page.expect_request(lambda request: request.url == "http://example.com" and request.method == "get") as second:
page.click('img') page.get_by_text("trigger request").click()
second_request = second.value second_request = second.value
``` ```
@ -4199,13 +4182,13 @@ second_request = second.value
// Waits for the next request with the specified url. // Waits for the next request with the specified url.
await page.RunAndWaitForRequestAsync(async () => await page.RunAndWaitForRequestAsync(async () =>
{ {
await page.ClickAsync("button"); await page.GetByText("trigger request").ClickAsync();
}, "http://example.com/resource"); }, "http://example.com/resource");
// Alternative way with a predicate. // Alternative way with a predicate.
await page.RunAndWaitForRequestAsync(async () => await page.RunAndWaitForRequestAsync(async () =>
{ {
await page.ClickAsync("button"); await page.GetByText("trigger request").ClickAsync();
}, request => request.Url == "https://example.com" && request.Method == "GET"); }, request => request.Url == "https://example.com" && request.Method == "GET");
``` ```
@ -4266,60 +4249,53 @@ Returns the matched response. See [waiting for event](../events.md#waiting-for-e
**Usage** **Usage**
```js ```js
// Note that Promise.all prevents a race condition // Start waiting for response before clicking. Note no await.
// between clicking and waiting for the response. const responsePromise = page.waitForRequest('https://example.com/resource');
const [response] = await Promise.all([ await page.getByText('trigger response').click();
// Waits for the next response with the specified url const response = await responsePromise;
page.waitForResponse('https://example.com/resource'),
// Triggers the response
page.click('button.triggers-response'),
]);
// Alternative way with a predicate. // Alternative way with a predicate. Note no await.
const [response] = await Promise.all([ const responsePromise = page.waitForRequest(response => response.url() === 'https://example.com' && response.status() === 200);
// Waits for the next response matching some conditions await page.getByText('trigger response').click();
page.waitForResponse(response => response.url() === 'https://example.com' && response.status() === 200), const response = await responsePromise;
// Triggers the response
page.click('button.triggers-response'),
]);
``` ```
```java ```java
// Waits for the next response with the specified url // Waits for the next response with the specified url
Response response = page.waitForResponse("https://example.com/resource", () -> { Response response = page.waitForResponse("https://example.com/resource", () -> {
// Triggers the response // Triggers the response
page.click("button.triggers-response"); page.getByText("trigger response").click();
}); });
// Waits for the next response matching some conditions // Waits for the next response matching some conditions
Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> { Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
// Triggers the response // Triggers the response
page.click("button.triggers-response"); page.getByText("trigger response").click();
}); });
``` ```
```python async ```python async
async with page.expect_response("https://example.com/resource") as response_info: async with page.expect_response("https://example.com/resource") as response_info:
await page.click("input") await page.get_by_text("trigger response").click()
response = await response_info.value response = await response_info.value
return response.ok return response.ok
# or with a lambda # or with a lambda
async with page.expect_response(lambda response: response.url == "https://example.com" and response.status == 200) as response_info: async with page.expect_response(lambda response: response.url == "https://example.com" and response.status == 200) as response_info:
await page.click("input") await page.get_by_text("trigger response").click()
response = await response_info.value response = await response_info.value
return response.ok return response.ok
``` ```
```python sync ```python sync
with page.expect_response("https://example.com/resource") as response_info: with page.expect_response("https://example.com/resource") as response_info:
page.click("input") page.get_by_text("trigger response").click()
response = response_info.value response = response_info.value
return response.ok return response.ok
# or with a lambda # or with a lambda
with page.expect_response(lambda response: response.url == "https://example.com" and response.status == 200) as response_info: with page.expect_response(lambda response: response.url == "https://example.com" and response.status == 200) as response_info:
page.click("input") page.get_by_text("trigger response").click()
response = response_info.value response = response_info.value
return response.ok return response.ok
``` ```
@ -4328,13 +4304,13 @@ return response.ok
// Waits for the next response with the specified url. // Waits for the next response with the specified url.
await page.RunAndWaitForResponseAsync(async () => await page.RunAndWaitForResponseAsync(async () =>
{ {
await page.ClickAsync("button.triggers-response"); await page.GetByText("trigger response").ClickAsync();
}, "http://example.com/resource"); }, "http://example.com/resource");
// Alternative way with a predicate. // Alternative way with a predicate.
await page.RunAndWaitForResponseAsync(async () => await page.RunAndWaitForResponseAsync(async () =>
{ {
await page.ClickAsync("button"); await page.GetByText("trigger response").ClickAsync();
}, response => response.Url == "https://example.com" && response.Status == 200); }, response => response.Url == "https://example.com" && response.Status == 200);
``` ```

View file

@ -281,10 +281,9 @@ Returns resource timing information for given request. Most of the timing values
**Usage** **Usage**
```js ```js
const [request] = await Promise.all([ const requestFinishedPromise = page.waitForEvent('requestfinished');
page.waitForEvent('requestfinished'), await page.goto('http://example.com');
page.goto('http://example.com') const request = await requestFinishedPromise;
]);
console.log(request.timing()); console.log(request.timing());
``` ```

View file

@ -16,12 +16,10 @@ Downloaded files are deleted when the browser context that produced them is clos
Here is the simplest way to handle the file download: Here is the simplest way to handle the file download:
```js ```js
const [ download ] = await Promise.all([ // Start waiting for download before clicking. Note no await.
// Start waiting for the download const downloadPromise = page.waitForEvent('download');
page.waitForEvent('download'), await page.getByText('Download file').click();
// Perform the action that initiates download const download = await downloadPromise;
page.locator('button#delayed-download').click(),
]);
// Wait for the download process to complete // Wait for the download process to complete
console.log(await download.path()); console.log(await download.path());
// Save downloaded file somewhere // Save downloaded file somewhere
@ -32,7 +30,7 @@ await download.saveAs('/path/to/save/download/at.txt');
// Wait for the download to start // Wait for the download to start
Download download = page.waitForDownload(() -> { Download download = page.waitForDownload(() -> {
// Perform the action that initiates download // Perform the action that initiates download
page.locator("button#delayed-download").click(); page.getByText("Download file").click();
}); });
// Wait for the download process to complete // Wait for the download process to complete
Path path = download.path(); Path path = download.path();
@ -45,7 +43,7 @@ download.saveAs(Paths.get("/path/to/save/download/at.txt"));
# Start waiting for the download # Start waiting for the download
async with page.expect_download() as download_info: async with page.expect_download() as download_info:
# Perform the action that initiates download # Perform the action that initiates download
await page.locator("button#delayed-download").click() await page.get_by_text("Download file").click()
download = await download_info.value download = await download_info.value
# Wait for the download process to complete # Wait for the download process to complete
print(await download.path()) print(await download.path())
@ -57,7 +55,8 @@ download.save_as("/path/to/save/download/at.txt")
# Start waiting for the download # Start waiting for the download
with page.expect_download() as download_info: with page.expect_download() as download_info:
# Perform the action that initiates download # Perform the action that initiates download
page.locator("button#delayed-download").click() page.get_by_text("Download file").click()
# Wait for the download to start
download = download_info.value download = download_info.value
# Wait for the download process to complete # Wait for the download process to complete
print(download.path()) print(download.path())
@ -66,12 +65,11 @@ download.save_as("/path/to/save/download/at.txt")
``` ```
```csharp ```csharp
// Start the task of waiting for the download // Start the task of waiting for the download before clicking
var waitForDownloadTask = page.WaitForDownloadAsync(); var waitForDownloadTask = page.WaitForDownloadAsync();
// Perform the action that initiates download await page.GetByText("Download file").ClickAsync();
await page.Locator("#downloadButton").ClickAsync();
// Wait for the download process to complete
var download = await waitForDownloadTask; var download = await waitForDownloadTask;
// Wait for the download process to complete
Console.WriteLine(await download.PathAsync()); Console.WriteLine(await download.PathAsync());
// Save downloaded file somewhere // Save downloaded file somewhere
await download.SaveAsAsync("/path/to/save/download/at.txt"); await download.SaveAsAsync("/path/to/save/download/at.txt");

View file

@ -12,13 +12,10 @@ Most of the time, scripts will need to wait for a particular event to happen. Be
Wait for a request with the specified url using [`method: Page.waitForRequest`]: Wait for a request with the specified url using [`method: Page.waitForRequest`]:
```js ```js
// Note that Promise.all prevents a race condition // Start waiting for request before goto. Note no await.
// between clicking and waiting for the request. const requestPromise = page.waitForRequest('**/*logo*.png');
const [request] = await Promise.all([ await page.goto('https://wikipedia.org');
page.waitForRequest('**/*logo*.png'), const request = await requestPromise;
// This action triggers the request
page.goto('https://wikipedia.org')
]);
console.log(request.url()); console.log(request.url());
``` ```
@ -54,14 +51,10 @@ Console.WriteLine(request.Url);
Wait for popup window: Wait for popup window:
```js ```js
// Note that Promise.all prevents a race condition // Start waiting for popup before clicking. Note no await.
// between clicking and waiting for the popup. const popupPromise = page.waitForEvent('popup');
const [popup] = await Promise.all([ await page.getByText('open the popup').click();
// It is important to call waitForEvent first. const popup = await popupPromise;
page.waitForEvent('popup'),
// This action triggers the popup
page.evaluate('window.open()')
]);
await popup.goto('https://wikipedia.org'); await popup.goto('https://wikipedia.org');
``` ```
@ -69,28 +62,28 @@ await popup.goto('https://wikipedia.org');
// The callback lambda defines scope of the code that is expected to // The callback lambda defines scope of the code that is expected to
// create popup window. // create popup window.
Page popup = page.waitForPopup(() -> { Page popup = page.waitForPopup(() -> {
page.evaluate("window.open()"); page.getByText("open the popup").click();
}); });
popup.navigate("https://wikipedia.org"); popup.navigate("https://wikipedia.org");
``` ```
```python async ```python async
async with page.expect_popup() as popup: async with page.expect_popup() as popup:
await page.evaluate("window.open()") await page.get_by_text("open the popup").click()
child_page = await popup.value child_page = await popup.value
await child_page.goto("https://wikipedia.org") await child_page.goto("https://wikipedia.org")
``` ```
```python sync ```python sync
with page.expect_popup() as popup: with page.expect_popup() as popup:
page.evaluate("window.open()") page.get_by_text("open the popup").click()
popup.value.goto("https://wikipedia.org") popup.value.goto("https://wikipedia.org")
``` ```
```csharp ```csharp
var popup = await page.RunAndWaitForPopupAsync(async => var popup = await page.RunAndWaitForPopupAsync(async =>
{ {
await page.EvaluateAsync("window.open()"); await page.GetByText("open the popup").ClickAsync();
}); });
await popup.GotoAsync("https://wikipedia.org"); await popup.GotoAsync("https://wikipedia.org");
``` ```

View file

@ -606,33 +606,30 @@ If you don't have input element in hand (it is created dynamically), you can han
or use a corresponding waiting method upon your action: or use a corresponding waiting method upon your action:
```js ```js
// Note that Promise.all prevents a race condition // Start waiting for file chooser before clicking. Note no await.
// between clicking and waiting for the file chooser. const fileChooserPromise = page.waitForEvent('filechooser');
const [fileChooser] = await Promise.all([ await page.getByLabel('Upload file').click();
// It is important to call waitForEvent before click to set up waiting. const fileChooser = await fileChooserPromise;
page.waitForEvent('filechooser'),
page.locator('upload').click(),
]);
await fileChooser.setFiles('myfile.pdf'); await fileChooser.setFiles('myfile.pdf');
``` ```
```java ```java
FileChooser fileChooser = page.waitForFileChooser(() -> { FileChooser fileChooser = page.waitForFileChooser(() -> {
page.locator("upload").click(); page.getByLabel("Upload file").click();
}); });
fileChooser.setFiles(Paths.get("myfile.pdf")); fileChooser.setFiles(Paths.get("myfile.pdf"));
``` ```
```python async ```python async
async with page.expect_file_chooser() as fc_info: async with page.expect_file_chooser() as fc_info:
await page.locator("upload").click() await page.get_by_label("Upload file").click()
file_chooser = await fc_info.value file_chooser = await fc_info.value
await file_chooser.set_files("myfile.pdf") await file_chooser.set_files("myfile.pdf")
``` ```
```python sync ```python sync
with page.expect_file_chooser() as fc_info: with page.expect_file_chooser() as fc_info:
page.locator("upload").click() page.get_by_label("Upload file").click()
file_chooser = fc_info.value file_chooser = fc_info.value
file_chooser.set_files("myfile.pdf") file_chooser.set_files("myfile.pdf")
``` ```
@ -640,7 +637,7 @@ file_chooser.set_files("myfile.pdf")
```csharp ```csharp
var fileChooser = page.RunAndWaitForFileChooserAsync(async () => var fileChooser = page.RunAndWaitForFileChooserAsync(async () =>
{ {
await page.Locator("upload").ClickAsync(); await page.GetByLabel("Upload file").ClickAsync();
}); });
await fileChooser.SetFilesAsync("myfile.pdf"); await fileChooser.SetFilesAsync("myfile.pdf");
``` ```

View file

@ -299,22 +299,17 @@ recommended to explicitly call [`method: Page.waitForNavigation`]. For example:
* Page waits for network requests before navigation * Page waits for network requests before navigation
```js ```js
// Note that Promise.all prevents a race condition // Start waiting for navigation before clicking. Note no await.
// between clicking and waiting for a navigation. const navigationPromise = page.waitForNavigation();
await Promise.all([ await page.getByText('Navigate after timeout').click();
// Waits for the next navigation. await navigationPromise;
// It is important to call waitForNavigation before click to set up waiting.
page.waitForNavigation(),
// Triggers a navigation after a timeout.
page.locator('div.delayed-navigation').click(),
]);
``` ```
```java ```java
// Using waitForNavigation with a callback prevents a race condition // Using waitForNavigation with a callback prevents a race condition
// between clicking and waiting for a navigation. // between clicking and waiting for a navigation.
page.waitForNavigation(() -> { // Waits for the next navigation page.waitForNavigation(() -> { // Waits for the next navigation
page.locator("div.delayed-navigation").click(); // Triggers a navigation after a timeout page.getByText("Navigate after timeout").click(); // Triggers a navigation after a timeout
}); });
``` ```
@ -323,7 +318,7 @@ page.waitForNavigation(() -> { // Waits for the next navigation
# prevents a race condition between clicking and waiting for a navigation. # prevents a race condition between clicking and waiting for a navigation.
async with page.expect_navigation(): async with page.expect_navigation():
# Triggers a navigation after a timeout # Triggers a navigation after a timeout
await page.locator("div.delayed-navigation").click() await page.get_by_text("Navigate after timeout").click()
``` ```
```python sync ```python sync
@ -331,7 +326,7 @@ async with page.expect_navigation():
# prevents a race condition between clicking and waiting for a navigation. # prevents a race condition between clicking and waiting for a navigation.
with page.expect_navigation(): with page.expect_navigation():
# Triggers a navigation after a timeout # Triggers a navigation after a timeout
page.locator("a").click() page.get_by_text("Navigate after timeout").click()
``` ```
```csharp ```csharp
@ -340,7 +335,7 @@ with page.expect_navigation():
await page.RunAndWaitForNavigationAsync(async () => await page.RunAndWaitForNavigationAsync(async () =>
{ {
// Triggers a navigation after a timeout // Triggers a navigation after a timeout
await page.Locator("div.delayed-navigation").ClickAsync(); await page.GetByText("Navigate after timeout").ClickAsync();
}); });
``` ```
@ -352,14 +347,11 @@ Clicking an element could trigger multiple navigations. In these cases, it is re
* Multiple pushes to history state * Multiple pushes to history state
```js ```js
// Note that Promise.all prevents a race condition // Start waiting for navigation before clicking. Note no await.
// between clicking and waiting for a navigation. const navigationPromise = page.waitForNavigation({ url: '**/login' });
await Promise.all([ // This action triggers the navigation with a script redirect.
// It is important to call waitForNavigation before click to set up waiting. await page.getByText('Click me').click();
page.waitForNavigation({ url: '**/login' }), await navigationPromise;
// Triggers a navigation with a script redirect.
page.getByText('Click me').click(),
]);
``` ```
```java ```java
@ -404,34 +396,31 @@ await page.RunAndWaitForNavigationAsync(async () =>
When popup is opened, explicitly calling [`method: Page.waitForLoadState`] ensures that popup is loaded to the desired state. When popup is opened, explicitly calling [`method: Page.waitForLoadState`] ensures that popup is loaded to the desired state.
```js ```js
// Note that Promise.all prevents a race condition // Start waiting for popup before clicking. Note no await.
// between clicking and waiting for the popup. const popupPromise = page.waitForEvent('popup');
const [ popup ] = await Promise.all([ await page.getByText('Open popup').click();
// It is important to call waitForEvent before click to set up waiting. const popup = await popupPromise;
page.waitForEvent('popup'), // Wait for the popup to load.
// Opens popup.
page.locator('a[target="_blank"]').click(),
]);
await popup.waitForLoadState('load'); await popup.waitForLoadState('load');
``` ```
```java ```java
Page popup = page.waitForPopup(() -> { Page popup = page.waitForPopup(() -> {
page.locator("a[target='_blank']").click(); // Opens popup page.getByText("Open popup").click(); // Opens popup
}); });
popup.waitForLoadState(LoadState.LOAD); popup.waitForLoadState(LoadState.LOAD);
``` ```
```python async ```python async
async with page.expect_popup() as popup_info: async with page.expect_popup() as popup_info:
await page.locator('a[target="_blank"]').click() # Opens popup await page.get_by_text("Open popup").click() # Opens popup
popup = await popup_info.value popup = await popup_info.value
await popup.wait_for_load_state("load") await popup.wait_for_load_state("load")
``` ```
```python sync ```python sync
with page.expect_popup() as popup_info: with page.expect_popup() as popup_info:
page.locator('a[target="_blank"]').click() # Opens popup page.get_by_text("Open popup").click() # Opens popup
popup = popup_info.value popup = popup_info.value
popup.wait_for_load_state("load") popup.wait_for_load_state("load")
``` ```
@ -439,7 +428,7 @@ popup.wait_for_load_state("load")
```csharp ```csharp
var popup = await page.RunAndWaitForPopupAsync(async () => var popup = await page.RunAndWaitForPopupAsync(async () =>
{ {
await page.Locator("a[target='_blank']").ClickAsync(); // Opens popup await page.GetByText("Open popup").ClickAsync(); // Opens popup
}); });
popup.WaitForLoadStateAsync(LoadState.Load); popup.WaitForLoadStateAsync(LoadState.Load);
``` ```

View file

@ -248,11 +248,10 @@ await page.GotoAsync("https://example.com");
Or wait for a network response after the button click with [`method: Page.waitForResponse`]: Or wait for a network response after the button click with [`method: Page.waitForResponse`]:
```js ```js
// Use a glob URL pattern // Use a glob URL pattern. Note no await.
const [response] = await Promise.all([ const responsePromise = page.waitForResponse('**/api/fetch_data');
page.waitForResponse('**/api/fetch_data'), await page.getByText('Update').click();
page.getByText('Update').click(), const response = await responsePromise;
]);
``` ```
```java ```java
@ -288,17 +287,15 @@ var response = await waitForResponseTask;
Wait for [Response]s with [`method: Page.waitForResponse`] Wait for [Response]s with [`method: Page.waitForResponse`]
```js ```js
// Use a RegExp // Use a RegExp. Note no await.
const [response] = await Promise.all([ const responsePromise = page.waitForResponse(/\.jpeg$/);
page.waitForResponse(/\.jpeg$/), await page.getByText('Update').click();
page.getByText('Update').click(), const response = await responsePromise;
]);
// Use a predicate taking a Response object // Use a predicate taking a Response object. Note no await.
const [response] = await Promise.all([ const responsePromise = page.waitForResponse(response => response.url().includes(token));
page.waitForResponse(response => response.url().includes(token)), await page.getByText('Update').click();
page.getByText('Update').click(), const response = await responsePromise;
]);
``` ```
```java ```java

View file

@ -141,11 +141,10 @@ The `page` event on browser contexts can be used to get new pages that are creat
handle new pages opened by `target="_blank"` links. handle new pages opened by `target="_blank"` links.
```js ```js
// Get page after a specific action (e.g. clicking a link) // Start waiting for new page before clicking. Note no await.
const [newPage] = await Promise.all([ const pagePromise = context.waitForEvent('page');
context.waitForEvent('page'), await page.getByText('open new tab').click();
page.locator('a[target="_blank"]').click() // Opens a new tab const newPage = await pagePromise;
])
await newPage.waitForLoadState(); await newPage.waitForLoadState();
console.log(await newPage.title()); console.log(await newPage.title());
``` ```
@ -153,7 +152,7 @@ console.log(await newPage.title());
```java ```java
// Get page after a specific action (e.g. clicking a link) // Get page after a specific action (e.g. clicking a link)
Page newPage = context.waitForPage(() -> { Page newPage = context.waitForPage(() -> {
page.locator("a[target='_blank']").click(); // Opens a new tab page.getByText("open new tab").click(); // Opens a new tab
}); });
newPage.waitForLoadState(); newPage.waitForLoadState();
System.out.println(newPage.title()); System.out.println(newPage.title());
@ -162,7 +161,7 @@ System.out.println(newPage.title());
```python async ```python async
# Get page after a specific action (e.g. clicking a link) # Get page after a specific action (e.g. clicking a link)
async with context.expect_page() as new_page_info: async with context.expect_page() as new_page_info:
await page.locator('a[target="_blank"]').click() # Opens a new tab await page.get_by_text("open new tab").click() # Opens a new tab
new_page = await new_page_info.value new_page = await new_page_info.value
await new_page.wait_for_load_state() await new_page.wait_for_load_state()
@ -172,7 +171,7 @@ print(await new_page.title())
```python sync ```python sync
# Get page after a specific action (e.g. clicking a link) # Get page after a specific action (e.g. clicking a link)
with context.expect_page() as new_page_info: with context.expect_page() as new_page_info:
page.locator('a[target="_blank"]').click() # Opens a new tab page.get_by_text("open new tab").click() # Opens a new tab
new_page = new_page_info.value new_page = new_page_info.value
new_page.wait_for_load_state() new_page.wait_for_load_state()
@ -183,7 +182,7 @@ print(new_page.title())
// Get page after a specific action (e.g. clicking a link) // Get page after a specific action (e.g. clicking a link)
var newPage = await context.RunAndWaitForPageAsync(async () => var newPage = await context.RunAndWaitForPageAsync(async () =>
{ {
await page.Locator("a[target='_blank']").ClickAsync(); await page.GetByText("open new tab").ClickAsync();
}); });
await newPage.WaitForLoadStateAsync(); await newPage.WaitForLoadStateAsync();
Console.WriteLine(await newPage.TitleAsync()); Console.WriteLine(await newPage.TitleAsync());
@ -241,14 +240,11 @@ If the page opens a pop-up (e.g. pages opened by `target="_blank"` links), you c
This event is emitted in addition to the `browserContext.on('page')` event, but only for popups relevant to this page. This event is emitted in addition to the `browserContext.on('page')` event, but only for popups relevant to this page.
```js ```js
// Note that Promise.all prevents a race condition // Start waiting for popup before clicking. Note no await.
// between clicking and waiting for the popup. const popupPromise = page.waitForEvent('popup');
const [popup] = await Promise.all([ await page.getByText('open the popup').click();
// It is important to call waitForEvent before click to set up waiting. const popup = await popupPromise;
page.waitForEvent('popup'), // Wait for the popup to load.
// Opens popup.
page.locator('#open').click(),
]);
await popup.waitForLoadState(); await popup.waitForLoadState();
console.log(await popup.title()); console.log(await popup.title());
``` ```
@ -256,7 +252,7 @@ console.log(await popup.title());
```java ```java
// Get popup after a specific action (e.g., click) // Get popup after a specific action (e.g., click)
Page popup = page.waitForPopup(() -> { Page popup = page.waitForPopup(() -> {
page.locator("#open").click(); page.getByText("open the popup").click();
}); });
popup.waitForLoadState(); popup.waitForLoadState();
System.out.println(popup.title()); System.out.println(popup.title());
@ -265,7 +261,7 @@ System.out.println(popup.title());
```python async ```python async
# Get popup after a specific action (e.g., click) # Get popup after a specific action (e.g., click)
async with page.expect_popup() as popup_info: async with page.expect_popup() as popup_info:
await page.locator("#open").click() await page.get_by_text("open the popup").click()
popup = await popup_info.value popup = await popup_info.value
await popup.wait_for_load_state() await popup.wait_for_load_state()
@ -275,7 +271,7 @@ print(await popup.title())
```python sync ```python sync
# Get popup after a specific action (e.g., click) # Get popup after a specific action (e.g., click)
with page.expect_popup() as popup_info: with page.expect_popup() as popup_info:
page.locator("#open").click() page.get_by_text("open the popup").click()
popup = popup_info.value popup = popup_info.value
popup.wait_for_load_state() popup.wait_for_load_state()
@ -284,12 +280,12 @@ print(popup.title())
```csharp ```csharp
// Get popup after a specific action (e.g., click) // Get popup after a specific action (e.g., click)
var newPage = await page.RunAndWaitForPopupAsync(async () => var popup = await page.RunAndWaitForPopupAsync(async () =>
{ {
await page.Locator("#open").ClickAsync(); await page.GetByText("open the popup").ClickAsync();
}); });
await newPage.WaitForLoadStateAsync(); await popup.WaitForLoadStateAsync();
Console.WriteLine(await newPage.TitleAsync()); Console.WriteLine(await popup.TitleAsync());
``` ```
If the action that triggers the popup is unknown, the following pattern can be used. If the action that triggers the popup is unknown, the following pattern can be used.
@ -298,7 +294,7 @@ If the action that triggers the popup is unknown, the following pattern can be u
// Get all popups when they open // Get all popups when they open
page.on('popup', async popup => { page.on('popup', async popup => {
await popup.waitForLoadState(); await popup.waitForLoadState();
await popup.title(); console.log(await popup.title());
}) })
``` ```

View file

@ -28,17 +28,15 @@ If you're using (or are interested in using this this feature), please comment o
You can use [`method: BrowserContext.serviceWorkers`] to list the Service [Worker]s, or specifically watch for the Service [Worker] if you anticipate a page will trigger its [registration](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register): You can use [`method: BrowserContext.serviceWorkers`] to list the Service [Worker]s, or specifically watch for the Service [Worker] if you anticipate a page will trigger its [registration](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register):
```js tab=js-ts ```js tab=js-ts
const [ serviceworker ] = await Promise.all([ const serviceWorkerPromise = context.waitForEvent('serviceworker');
context.waitForEvent('serviceworker'), await page.goto('/example-with-a-service-worker.html');
page.goto('/example-with-a-service-worker.html'), const serviceworker = await serviceWorkerPromise;
]);
``` ```
```js tab=js-js ```js tab=js-js
const [ serviceworker ] = await Promise.all([ const serviceWorkerPromise = context.waitForEvent('serviceworker');
context.waitForEvent('serviceworker'), await page.goto('/example-with-a-service-worker.html');
page.goto('/example-with-a-service-worker.html'), const serviceworker = await serviceWorkerPromise;
]);
``` ```
```python async ```python async
@ -148,7 +146,7 @@ Many Service Worker implementations simply execute the request from the page (po
// filename: transparent-service-worker.js // filename: transparent-service-worker.js
self.addEventListener("fetch", (event) => { self.addEventListener("fetch", (event) => {
// actually make the request // actually make the request
const responsePromise = fetch(event.request); const responsePromise = fetch(event.request);
// send it back to the page // send it back to the page
event.respondWith(responsePromise); event.respondWith(responsePromise);
}); });

View file

@ -990,14 +990,10 @@ export interface Page {
* "http://example.com" is done and its response has started loading in the popup. * "http://example.com" is done and its response has started loading in the popup.
* *
* ```js * ```js
* // Note that Promise.all prevents a race condition * // Start waiting for popup before clicking. Note no await.
* // between evaluating and waiting for the popup. * const popupPromise = page.waitForEvent('popup');
* const [popup] = await Promise.all([ * await page.getByText('open the popup').click();
* // It is important to call waitForEvent first. * const popup = await popupPromise;
* page.waitForEvent('popup'),
* // Opens the popup.
* page.evaluate(() => window.open('https://example.com')),
* ]);
* console.log(await popup.evaluate('location.href')); * console.log(await popup.evaluate('location.href'));
* ``` * ```
* *
@ -1287,14 +1283,10 @@ export interface Page {
* "http://example.com" is done and its response has started loading in the popup. * "http://example.com" is done and its response has started loading in the popup.
* *
* ```js * ```js
* // Note that Promise.all prevents a race condition * // Start waiting for popup before clicking. Note no await.
* // between evaluating and waiting for the popup. * const popupPromise = page.waitForEvent('popup');
* const [popup] = await Promise.all([ * await page.getByText('open the popup').click();
* // It is important to call waitForEvent first. * const popup = await popupPromise;
* page.waitForEvent('popup'),
* // Opens the popup.
* page.evaluate(() => window.open('https://example.com')),
* ]);
* console.log(await popup.evaluate('location.href')); * console.log(await popup.evaluate('location.href'));
* ``` * ```
* *
@ -1679,14 +1671,10 @@ export interface Page {
* "http://example.com" is done and its response has started loading in the popup. * "http://example.com" is done and its response has started loading in the popup.
* *
* ```js * ```js
* // Note that Promise.all prevents a race condition * // Start waiting for popup before clicking. Note no await.
* // between evaluating and waiting for the popup. * const popupPromise = page.waitForEvent('popup');
* const [popup] = await Promise.all([ * await page.getByText('open the popup').click();
* // It is important to call waitForEvent first. * const popup = await popupPromise;
* page.waitForEvent('popup'),
* // Opens the popup.
* page.evaluate(() => window.open('https://example.com')),
* ]);
* console.log(await popup.evaluate('location.href')); * console.log(await popup.evaluate('location.href'));
* ``` * ```
* *
@ -4214,14 +4202,10 @@ export interface Page {
* "http://example.com" is done and its response has started loading in the popup. * "http://example.com" is done and its response has started loading in the popup.
* *
* ```js * ```js
* // Note that Promise.all prevents a race condition * // Start waiting for popup before clicking. Note no await.
* // between evaluating and waiting for the popup. * const popupPromise = page.waitForEvent('popup');
* const [popup] = await Promise.all([ * await page.getByText('open the popup').click();
* // It is important to call waitForEvent first. * const popup = await popupPromise;
* page.waitForEvent('popup'),
* // Opens the popup.
* page.evaluate(() => window.open('https://example.com')),
* ]);
* console.log(await popup.evaluate('location.href')); * console.log(await popup.evaluate('location.href'));
* ``` * ```
* *
@ -4295,13 +4279,10 @@ export interface Page {
* ``` * ```
* *
* ```js * ```js
* const [popup] = await Promise.all([ * const popupPromise = page.waitForEvent('popup');
* // It is important to call waitForEvent before click to set up waiting. * await page.getByRole('button').click(); // Click triggers a popup.
* page.waitForEvent('popup'), * const popup = await popupPromise;
* // Click triggers a popup. * await popup.waitForLoadState('domcontentloaded'); // Wait for the 'DOMContentLoaded' event.
* page.getByRole('button').click(),
* ])
* await popup.waitForLoadState('domcontentloaded'); // The promise resolves after 'domcontentloaded' event.
* console.log(await popup.title()); // Popup is ready to use. * console.log(await popup.title()); // Popup is ready to use.
* ``` * ```
* *
@ -4336,14 +4317,10 @@ export interface Page {
* a `setTimeout`. Consider this example: * a `setTimeout`. Consider this example:
* *
* ```js * ```js
* // Note that Promise.all prevents a race condition * // Start waiting for navigation before clicking. Note no await.
* // between clicking and waiting for the navigation. * const navigationPromise = page.waitForNavigation();
* const [response] = await Promise.all([ * await page.getByText('Navigate after timeout').click();
* // It is important to call waitForNavigation before click to set up waiting. * await navigationPromise;
* page.waitForNavigation(),
* // Clicking the link will indirectly cause a navigation.
* page.locator('a.delayed-navigation').click(),
* ]);
* ``` * ```
* *
* **NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL * **NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL
@ -4387,22 +4364,15 @@ export interface Page {
* **Usage** * **Usage**
* *
* ```js * ```js
* // Note that Promise.all prevents a race condition * // Start waiting for request before clicking. Note no await.
* // between clicking and waiting for the request. * const requestPromise = page.waitForRequest('https://example.com/resource');
* const [request] = await Promise.all([ * await page.getByText('trigger request').click();
* // Waits for the next request with the specified url * const request = await requestPromise;
* page.waitForRequest('https://example.com/resource'),
* // Triggers the request
* page.click('button.triggers-request'),
* ]);
* *
* // Alternative way with a predicate. * // Alternative way with a predicate. Note no await.
* const [request] = await Promise.all([ * const requestPromise = page.waitForRequest(request => request.url() === 'https://example.com' && request.method() === 'GET');
* // Waits for the next request matching some conditions * await page.getByText('trigger request').click();
* page.waitForRequest(request => request.url() === 'https://example.com' && request.method() === 'GET'), * const request = await requestPromise;
* // Triggers the request
* page.click('button.triggers-request'),
* ]);
* ``` * ```
* *
* @param urlOrPredicate Request URL string, regex or predicate receiving [Request] object. * @param urlOrPredicate Request URL string, regex or predicate receiving [Request] object.
@ -4424,22 +4394,15 @@ export interface Page {
* **Usage** * **Usage**
* *
* ```js * ```js
* // Note that Promise.all prevents a race condition * // Start waiting for response before clicking. Note no await.
* // between clicking and waiting for the response. * const responsePromise = page.waitForRequest('https://example.com/resource');
* const [response] = await Promise.all([ * await page.getByText('trigger response').click();
* // Waits for the next response with the specified url * const response = await responsePromise;
* page.waitForResponse('https://example.com/resource'),
* // Triggers the response
* page.click('button.triggers-response'),
* ]);
* *
* // Alternative way with a predicate. * // Alternative way with a predicate. Note no await.
* const [response] = await Promise.all([ * const responsePromise = page.waitForRequest(response => response.url() === 'https://example.com' && response.status() === 200);
* // Waits for the next response matching some conditions * await page.getByText('trigger response').click();
* page.waitForResponse(response => response.url() === 'https://example.com' && response.status() === 200), * const response = await responsePromise;
* // Triggers the response
* page.click('button.triggers-response'),
* ]);
* ``` * ```
* *
* @param urlOrPredicate Request URL string, regex or predicate receiving [Response] object. When a `baseURL` via the context options was * @param urlOrPredicate Request URL string, regex or predicate receiving [Response] object. When a `baseURL` via the context options was
@ -6916,10 +6879,10 @@ export interface Frame {
* cause the frame to navigate. Consider this example: * cause the frame to navigate. Consider this example:
* *
* ```js * ```js
* const [response] = await Promise.all([ * // Start waiting for navigation before clicking. Note no await.
* frame.waitForNavigation(), // The promise resolves after navigation has finished * const navigationPromise = page.waitForNavigation();
* frame.click('a.delayed-navigation'), // Clicking the link will indirectly cause a navigation * await page.getByText('Navigate after timeout').click();
* ]); * await navigationPromise;
* ``` * ```
* *
* **NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL * **NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL
@ -7204,10 +7167,9 @@ export interface BrowserContext {
* "http://example.com" is done and its response has started loading in the popup. * "http://example.com" is done and its response has started loading in the popup.
* *
* ```js * ```js
* const [newPage] = await Promise.all([ * const newPagePromise = context.waitForEvent('page');
* context.waitForEvent('page'), * await page.getByText('open new page').click();
* page.locator('a[target=_blank]').click(), * const newPage = await newPagePromise;
* ]);
* console.log(await newPage.evaluate('location.href')); * console.log(await newPage.evaluate('location.href'));
* ``` * ```
* *
@ -7333,10 +7295,9 @@ export interface BrowserContext {
* "http://example.com" is done and its response has started loading in the popup. * "http://example.com" is done and its response has started loading in the popup.
* *
* ```js * ```js
* const [newPage] = await Promise.all([ * const newPagePromise = context.waitForEvent('page');
* context.waitForEvent('page'), * await page.getByText('open new page').click();
* page.locator('a[target=_blank]').click(), * const newPage = await newPagePromise;
* ]);
* console.log(await newPage.evaluate('location.href')); * console.log(await newPage.evaluate('location.href'));
* ``` * ```
* *
@ -7502,10 +7463,9 @@ export interface BrowserContext {
* "http://example.com" is done and its response has started loading in the popup. * "http://example.com" is done and its response has started loading in the popup.
* *
* ```js * ```js
* const [newPage] = await Promise.all([ * const newPagePromise = context.waitForEvent('page');
* context.waitForEvent('page'), * await page.getByText('open new page').click();
* page.locator('a[target=_blank]').click(), * const newPage = await newPagePromise;
* ]);
* console.log(await newPage.evaluate('location.href')); * console.log(await newPage.evaluate('location.href'));
* ``` * ```
* *
@ -8036,10 +7996,9 @@ export interface BrowserContext {
* "http://example.com" is done and its response has started loading in the popup. * "http://example.com" is done and its response has started loading in the popup.
* *
* ```js * ```js
* const [newPage] = await Promise.all([ * const newPagePromise = context.waitForEvent('page');
* context.waitForEvent('page'), * await page.getByText('open new page').click();
* page.locator('a[target=_blank]').click(), * const newPage = await newPagePromise;
* ]);
* console.log(await newPage.evaluate('location.href')); * console.log(await newPage.evaluate('location.href'));
* ``` * ```
* *
@ -15289,13 +15248,11 @@ export interface BrowserServer {
* }); * });
* *
* // Get the next console log * // Get the next console log
* const [msg] = await Promise.all([ * const msgPromise = page.waitForEvent('console');
* page.waitForEvent('console'), * await page.evaluate(() => {
* // Issue console.log inside the page * console.log('hello', 42, { foo: 'bar' }); // Issue console.log inside the page
* page.evaluate(() => { * });
* console.log('hello', 42, { foo: 'bar' }); * const msg = await msgPromise;
* }),
* ]);
* *
* // Deconstruct console log arguments * // Deconstruct console log arguments
* await msg.args[0].jsonValue() // hello * await msg.args[0].jsonValue() // hello
@ -15539,16 +15496,13 @@ export interface Dialog {
* Download event is emitted once the download starts. Download path becomes available once download completes: * Download event is emitted once the download starts. Download path becomes available once download completes:
* *
* ```js * ```js
* // Note that Promise.all prevents a race condition * // Start waiting for download before clicking. Note no await.
* // between clicking and waiting for the download. * const downloadPromise = page.waitForEvent('download');
* const [ download ] = await Promise.all([ * await page.getByText('Download file').click();
* // It is important to call waitForEvent before click to set up waiting. * const download = await downloadPromise;
* page.waitForEvent('download'), *
* // Triggers the download. * // Wait for the download process to complete.
* page.getByText('Download file').click(), * console.log(await download.path());
* ]);
* // wait for download to complete
* const path = await download.path();
* ``` * ```
* *
*/ */
@ -15843,14 +15797,10 @@ export interface Electron {
* [page.on('filechooser')](https://playwright.dev/docs/api/class-page#page-event-file-chooser) event. * [page.on('filechooser')](https://playwright.dev/docs/api/class-page#page-event-file-chooser) event.
* *
* ```js * ```js
* // Note that Promise.all prevents a race condition * // Start waiting for file chooser before clicking. Note no await.
* // between clicking and waiting for the file chooser. * const fileChooserPromise = page.waitForEvent('filechooser');
* const [fileChooser] = await Promise.all([ * await page.getByText('Upload file').click();
* // It is important to call waitForEvent before click to set up waiting. * const fileChooser = await fileChooserPromise;
* page.waitForEvent('filechooser'),
* // Opens the file chooser.
* page.getByText('Upload').click(),
* ]);
* await fileChooser.setFiles('myfile.pdf'); * await fileChooser.setFiles('myfile.pdf');
* ``` * ```
* *
@ -16794,10 +16744,9 @@ export interface Request {
* **Usage** * **Usage**
* *
* ```js * ```js
* const [request] = await Promise.all([ * const requestFinishedPromise = page.waitForEvent('requestfinished');
* page.waitForEvent('requestfinished'), * await page.goto('http://example.com');
* page.goto('http://example.com') * const request = await requestFinishedPromise;
* ]);
* console.log(request.timing()); * console.log(request.timing());
* ``` * ```
* *