docs(dotnet): examples for events, handles (#6598)

This commit is contained in:
Pavel Feldman 2021-05-15 11:57:20 -07:00 committed by GitHub
parent 9aa610063c
commit b5884b95b7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 92 additions and 12 deletions

View File

@ -109,7 +109,7 @@ page.once("load", lambda: print("page loaded!"))
``` ```
```csharp ```csharp
page.Load += (_, _) => { Console.WriteLine("Page loaded!"); }; page.Load += (_, _) => Console.WriteLine("Page loaded!");
``` ```
To unsubscribe from events use the `removeListener` method: To unsubscribe from events use the `removeListener` method:

View File

@ -49,6 +49,15 @@ with page.expect_request("**/*logo*.png") as first:
print(first.value.url) print(first.value.url)
``` ```
```csharp
// The callback lambda defines scope of the code that is expected to
// trigger request.
var waitForRequestTask = page.WaitForRequestAsync("**/*logo*.png");
await page.GotoAsync("https://wikipedia.org");
var request = await waitForRequestTask;
Console.WriteLine(request.Url);
```
Wait for popup window: Wait for popup window:
```js ```js
@ -84,6 +93,15 @@ with page.expect_popup() as popup:
popup.value.goto("https://wikipedia.org") popup.value.goto("https://wikipedia.org")
``` ```
```csharp
// The callback lambda defines scope of the code that is expected to
// create popup window.
var waitForPopupTask = page.WaitForPopupAsync();
await page.EvaluateAsync("window.open()");
var popup = await waitForPopupTask;
await popup.GotoAsync("https://wikipedia.org");
```
## Adding/removing event listener ## Adding/removing event listener
Sometimes, events happen in random time and instead of waiting for them, they need to be handled. Sometimes, events happen in random time and instead of waiting for them, they need to be handled.
@ -140,6 +158,19 @@ page.remove_listener("requestfinished", print_request_finished)
page.goto("https://www.openstreetmap.org/") page.goto("https://www.openstreetmap.org/")
``` ```
```csharp
page.Request += (_, request) => Console.WriteLine("Request sent: " + request.Url);
EventHandler<IRequest> listener = (_, request) => {
Console.WriteLine("Request finished: " + request.Url);
};
page.RequestFinished += listener;
await page.GotoAsync("https://wikipedia.org");
// Remove previously added listener, each on* method has corresponding off*
page.RequestFinished -= listener;
await page.GotoAsync("https://www.openstreetmap.org/");
```
## Adding one-off listeners ## Adding one-off listeners
If certain event needs to be handled once, there is a convenience API for that: If certain event needs to be handled once, there is a convenience API for that:
@ -164,6 +195,11 @@ page.once("dialog", lambda dialog: dialog.accept("2021"))
page.evaluate("prompt('Enter a number:')") page.evaluate("prompt('Enter a number:')")
``` ```
```csharp
page.Dialog += (_, dialog) => dialog.AcceptAsync("2021");
await page.EvaluateAsync("prompt('Enter a number:')");
```
### API reference ### API reference
- [Browser] - [Browser]

View File

@ -43,6 +43,11 @@ js_handle = page.evaluate_handle('window')
# Use jsHandle for evaluations. # Use jsHandle for evaluations.
``` ```
```csharp
var jsHandle = await page.EvaluateHandleAsync("window");
// Use jsHandle for evaluations.
```
```js ```js
const ulElementHandle = await page.waitForSelector('ul'); const ulElementHandle = await page.waitForSelector('ul');
// Use ulElementHandle for actions and evaluation. // Use ulElementHandle for actions and evaluation.
@ -63,6 +68,11 @@ ul_element_handle = page.wait_for_selector('ul')
# Use ul_element_handle for actions and evaluation. # Use ul_element_handle for actions and evaluation.
``` ```
```csharp
var ulElementHandle = await page.WaitForSelectorAsync("ul");
// Use ulElementHandle for actions and evaluation.
```
## Element Handles ## Element Handles
:::note :::note
@ -126,6 +136,20 @@ class_names = element_handle.get_attribute('class')
assert 'highlighted' in class_names assert 'highlighted' in class_names
``` ```
```csharp
// Get the element handle
var jsHandle = await page.WaitForSelectorAsync("#box");
var elementHandle = jsHandle as ElementHandle;
// Assert bounding box for the element
var boundingBox = await elementHandle.BoundingBoxAsync();
Assert.Equal(100, boundingBox.Width);
// Assert attribute for the element
var classNames = await elementHandle.GetAttributeAsync("class");
Assert.True(classNames.Contains("highlighted"));
```
## Handles as parameters ## Handles as parameters
Handles can be passed into the [`method: Page.evaluate`] and similar methods. Handles can be passed into the [`method: Page.evaluate`] and similar methods.
@ -213,6 +237,25 @@ page.evaluate("(arg) => arg.myArray.push(arg.newElement)", {
my_array_handle.dispose() my_array_handle.dispose()
``` ```
```csharp
// Create new array in page.
var myArrayHandle = await page.EvaluateHandleAsync("() => {\n" +
" window.myArray = [1];\n" +
" return myArray;\n" +
"}");
// Get the length of the array.
var length = await page.EvaluateAsync<int>("a => a.length", myArrayHandle);
// Add one more element to the array using the handle
await page.EvaluateAsync("arg => arg.myArray.add(arg.newElement)",
new { myArray = myArrayHandle, newElement = 2 });
// Release the object when it"s no longer needed.
await myArrayHandle.DisposeAsync();
```
## Handle Lifecycle ## Handle Lifecycle
Handles can be acquired using the page methods such as [`method: Page.evaluateHandle`], Handles can be acquired using the page methods such as [`method: Page.evaluateHandle`],

View File

@ -281,8 +281,7 @@ response = response_info.value
```csharp ```csharp
// Use a glob URL pattern // Use a glob URL pattern
var waitForResponseTask = page.WaitForResponseAsync( var waitForResponseTask = page.WaitForResponseAsync("**/api/fetch_data");
"**/api/fetch_data");
await Task.WhenAll( await Task.WhenAll(
waitForResponseTask, waitForResponseTask,
page.ClickAsync("button#update") page.ClickAsync("button#update")
@ -344,8 +343,7 @@ response = response_info.value
```csharp ```csharp
// Use a regular expression // Use a regular expression
var waitForResponseTask = page.WaitForResponseAsync( var waitForResponseTask = page.WaitForResponseAsync(new Regex("\\.jpeg$"));
new Regex("\\.jpeg$"));
await Task.WhenAll( await Task.WhenAll(
waitForResponseTask, waitForResponseTask,
page.ClickAsync("button#update") page.ClickAsync("button#update")
@ -353,8 +351,7 @@ await Task.WhenAll(
var response = waitForResponseTask.Result; var response = waitForResponseTask.Result;
// Use a predicate taking a Response object // Use a predicate taking a Response object
var waitForResponseTask = page.WaitForResponseAsync( var waitForResponseTask = page.WaitForResponseAsync(r => r.Url.Contains(token));
r => r.Url.Contains(token));
await Task.WhenAll( await Task.WhenAll(
waitForResponseTask, waitForResponseTask,
page.ClickAsync("button#update") page.ClickAsync("button#update")
@ -615,7 +612,8 @@ page.on("websocket", on_web_socket)
``` ```
```csharp ```csharp
page.WebSocket += (_, ws) => { page.WebSocket += (_, ws) =>
{
Console.WriteLine("WebSocket opened: " + ws.Url); Console.WriteLine("WebSocket opened: " + ws.Url);
ws.FrameSent += (_, f) => Console.WriteLine(f.Text); ws.FrameSent += (_, f) => Console.WriteLine(f.Text);
ws.FrameReceived += (_, f) => Console.WriteLine(f.Text); ws.FrameReceived += (_, f) => Console.WriteLine(f.Text);

View File

@ -95,7 +95,8 @@ msg.args[1].json_value() # 42
page.Console += (_, msg) => Console.WriteLine(msg.Text); page.Console += (_, msg) => Console.WriteLine(msg.Text);
// Listen for all console events and handle errors // Listen for all console events and handle errors
page.Console += (_, msg) => { page.Console += (_, msg) =>
{
if ("error".Equals(msg.Type)) if ("error".Equals(msg.Type))
Console.WriteLine("Error text: " + msg.Text); Console.WriteLine("Error text: " + msg.Text);
}; };
@ -161,7 +162,8 @@ page.goto("data:text/html,<script>throw new Error('test')</script>")
```csharp ```csharp
// Log all uncaught errors to the terminal // Log all uncaught errors to the terminal
page.PageError += (_, exception) => { page.PageError += (_, exception) =>
{
Console.WriteLine("Uncaught exception: " + exception); Console.WriteLine("Uncaught exception: " + exception);
}; };
``` ```
@ -211,8 +213,9 @@ page.on("dialog", lambda dialog: dialog.accept())
``` ```
```csharp ```csharp
page.RequestFailed += (_, request) => { page.RequestFailed += (_, request) =>
Console.WriteLine(request.Url + " " + request.Failure); {
Console.WriteLine(request.Url + " " + request.Failure);
}; };
``` ```