How to use Keyboard class of Microsoft.Playwright.Core package

Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Keyboard

Run Playwright-dotnet automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

PlaywrightPixelTest.cs

Source: PlaywrightPixelTest.cs Github

copy
1using Microsoft.Playwright;
2using System.Threading.Tasks;
3using System;
4using System.Collections.Generic;
5using Newtonsoft.Json;
6
7class PlaywrightPixelTest
8{
9    public static async Task main(string[] args)
10    {
11        using var playwright = await Playwright.CreateAsync();
12
13        Dictionary<string, string> browserstackOptions = new Dictionary<string, string>();
14        browserstackOptions.Add("name", "Test on Playwright emulated Pixel 5");
15        browserstackOptions.Add("build", "playwright-dotnet-4");
16        browserstackOptions.Add("browser", "playwright-webkit");  // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit`
17        browserstackOptions.Add("browserstack.username", "BROWSERSTACK_USERNAME");
18        browserstackOptions.Add("browserstack.accessKey", "BROWSERSTACK_ACCESS_KEY");
19        string capsJson = JsonConvert.SerializeObject(browserstackOptions);
20        string cdpUrl = "wss://cdp.browserstack.com/playwright?caps=" + Uri.EscapeDataString(capsJson);
21
22        await using var browser = await playwright.Chromium.ConnectAsync(cdpUrl);
23        
24        var context = await browser.NewContextAsync(playwright.Devices["Pixel 5"]);  // Complete list of devices - https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/deviceDescriptorsSource.json
25
26        var page = await context.NewPageAsync();
27        try {
28          await page.GotoAsync("https://www.google.co.in/");
29          await page.Locator("[aria-label='Search']").ClickAsync();
30          await page.FillAsync("[aria-label='Search']", "BrowserStack");
31          await page.Keyboard.PressAsync("Enter");
32          await page.Locator("[aria-current='page']").WaitForAsync();
33          var title = await page.TitleAsync();
34
35          if (title == "BrowserStack - Google Search")
36          {
37            // following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test
38            await MarkTestStatus("passed", "Title matched", page);
39          } else {
40            await MarkTestStatus("failed", "Title did not match", page);
41          }
42        }
43        catch (Exception err) {
44          await MarkTestStatus("failed", err.Message, page);
45        }
46        await browser.CloseAsync();
47    }
48
49    public static async Task MarkTestStatus(string status, string reason, IPage page) {
50        await page.EvaluateAsync("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"" + status + "\", \"reason\": \"" + reason + "\"}}");
51    }
52}
53
Full Screen

PlaywrightIPhoneTest.cs

Source: PlaywrightIPhoneTest.cs Github

copy
1using Microsoft.Playwright;
2using System.Threading.Tasks;
3using System;
4using System.Collections.Generic;
5using Newtonsoft.Json;
6
7class PlaywrightIPhoneTest
8{
9    public static async Task main(string[] args)
10    {
11        using var playwright = await Playwright.CreateAsync();
12
13        Dictionary<string, string> browserstackOptions = new Dictionary<string, string>();
14        browserstackOptions.Add("name", "Test on Playwright emulated IPhone 11 Pro");
15        browserstackOptions.Add("build", "playwright-dotnet-4");
16        browserstackOptions.Add("browser", "playwright-webkit");  // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit`
17        browserstackOptions.Add("browserstack.username", "BROWSERSTACK_USERNAME");
18        browserstackOptions.Add("browserstack.accessKey", "BROWSERSTACK_ACCESS_KEY");
19        string capsJson = JsonConvert.SerializeObject(browserstackOptions);
20        string cdpUrl = "wss://cdp.browserstack.com/playwright?caps=" + Uri.EscapeDataString(capsJson);
21
22        await using var browser = await playwright.Chromium.ConnectAsync(cdpUrl);
23        
24        var context = await browser.NewContextAsync(playwright.Devices["iPhone 11 Pro"]); // Complete list of devices - https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/deviceDescriptorsSource.json
25
26        var page = await context.NewPageAsync();
27        try {
28          await page.GotoAsync("https://www.google.co.in/");
29          await page.Locator("[aria-label='Search']").ClickAsync();
30          await page.FillAsync("[aria-label='Search']", "BrowserStack");
31          await page.Keyboard.PressAsync("Enter");
32          await page.Locator("[aria-current='page']").WaitForAsync();
33          var title = await page.TitleAsync();
34
35          if (title == "BrowserStack - Google Search")
36          {
37            // following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test
38            await MarkTestStatus("passed", "Title matched", page);
39          } else {
40            await MarkTestStatus("failed", "Title did not match", page);
41          }
42        }
43        catch (Exception err) {
44          await MarkTestStatus("failed", err.Message, page);
45        }
46        await browser.CloseAsync();
47    }
48  public static async Task MarkTestStatus(string status, string reason, IPage page) {
49        await page.EvaluateAsync("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"" + status + "\", \"reason\": \"" + reason + "\"}}");
50    }
51}
52
Full Screen

Keyboard.cs

Source: Keyboard.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Microsoft Corporation.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25using System.Threading.Tasks;
26using Microsoft.Playwright.Transport.Channels;
27
28namespace Microsoft.Playwright.Core
29{
30    internal class Keyboard : IKeyboard
31    {
32        private readonly PageChannel _channel;
33
34        public Keyboard(PageChannel channel)
35        {
36            _channel = channel;
37        }
38
39        public Task DownAsync(string key) => _channel.KeyboardDownAsync(key);
40
41        public Task UpAsync(string key) => _channel.KeyboardUpAsync(key);
42
43        public Task PressAsync(string key, KeyboardPressOptions options = default)
44           => _channel.PressAsync(key, options?.Delay);
45
46        public Task TypeAsync(string text, KeyboardTypeOptions options = default)
47           => _channel.TypeAsync(text, options?.Delay);
48
49        public Task InsertTextAsync(string text) => _channel.InsertTextAsync(text);
50    }
51}
52
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)