How to use FocusAsync method of PuppeteerSharp.Frame class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Frame.FocusAsync

ElementHandle.cs

Source:ElementHandle.cs Github

copy

Full Screen

...191 /// <summary>192 /// Calls <c>focus</c> <see href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus"/> on the element.193 /// </summary>194 /// <returns>Task</returns>195 public Task FocusAsync() => ExecutionContext.EvaluateFunctionAsync("element => element.focus()", this);196 /// <summary>197 /// Focuses the element, and sends a <c>keydown</c>, <c>keypress</c>/<c>input</c>, and <c>keyup</c> event for each character in the text.198 /// </summary>199 /// <param name="text">A text to type into a focused element</param>200 /// <param name="options">type options</param>201 /// <remarks>202 /// To press a special key, like <c>Control</c> or <c>ArrowDown</c> use <see cref="ElementHandle.PressAsync(string, PressOptions)"/>203 /// </remarks>204 /// <example>205 /// <code>206 /// elementHandle.TypeAsync("#mytextarea", "Hello"); // Types instantly207 /// elementHandle.TypeAsync("#mytextarea", "World", new TypeOptions { Delay = 100 }); // Types slower, like a user208 /// </code>209 /// An example of typing into a text field and then submitting the form:210 /// <code>211 /// var elementHandle = await page.GetElementAsync("input");212 /// await elementHandle.TypeAsync("some text");213 /// await elementHandle.PressAsync("Enter");214 /// </code>215 /// </example>216 /// <returns>Task</returns>217 public async Task TypeAsync(string text, TypeOptions options = null)218 {219 await FocusAsync().ConfigureAwait(false);220 await Page.Keyboard.TypeAsync(text, options).ConfigureAwait(false);221 }222 /// <summary>223 /// Focuses the element, and then uses <see cref="Keyboard.DownAsync(string, DownOptions)"/> and <see cref="Keyboard.UpAsync(string)"/>.224 /// </summary>225 /// <param name="key">Name of key to press, such as <c>ArrowLeft</c>. See <see cref="KeyDefinitions"/> for a list of all key names.</param>226 /// <param name="options">press options</param>227 /// <remarks>228 /// If <c>key</c> is a single character and no modifier keys besides <c>Shift</c> are being held down, a <c>keypress</c>/<c>input</c> event will also be generated. The <see cref="DownOptions.Text"/> option can be specified to force an input event to be generated.229 /// </remarks>230 /// <returns></returns>231 public async Task PressAsync(string key, PressOptions options = null)232 {233 await FocusAsync().ConfigureAwait(false);234 await Page.Keyboard.PressAsync(key, options).ConfigureAwait(false);235 }236 /// <summary>237 /// The method runs <c>element.querySelector</c> within the page. If no element matches the selector, the return value resolve to <c>null</c>.238 /// </summary>239 /// <param name="selector">A selector to query element for</param>240 /// <returns>Task which resolves to <see cref="ElementHandle"/> pointing to the frame element</returns>241 public async Task<ElementHandle> QuerySelectorAsync(string selector)242 {243 var handle = await ExecutionContext.EvaluateFunctionHandleAsync(244 "(element, selector) => element.querySelector(selector)",245 this, selector).ConfigureAwait(false);246 if (handle is ElementHandle element)247 {...

Full Screen

Full Screen

DOMWorld.cs

Source:DOMWorld.cs Github

copy

Full Screen

...262 }263 await handle.HoverAsync().ConfigureAwait(false);264 await handle.DisposeAsync().ConfigureAwait(false);265 }266 internal async Task FocusAsync(string selector)267 {268 var handle = await QuerySelectorAsync(selector).ConfigureAwait(false);269 if (handle == null)270 {271 throw new SelectorException($"No node found for selector: {selector}", selector);272 }273 await handle.FocusAsync().ConfigureAwait(false);274 await handle.DisposeAsync().ConfigureAwait(false);275 }276 internal async Task<string[]> SelectAsync(string selector, params string[] values)277 {278 if (!((await QuerySelectorAsync(selector).ConfigureAwait(false)) is ElementHandle handle))279 {280 throw new SelectorException($"No node found for selector: {selector}", selector);281 }282 var result = await handle.SelectAsync(values).ConfigureAwait(false);283 await handle.DisposeAsync();284 return result;285 }286 internal async Task TapAsync(string selector)287 {...

Full Screen

Full Screen

KeyboardTests.cs

Source:KeyboardTests.cs Github

copy

Full Screen

...70 [SkipBrowserFact(skipFirefox: true)]71 public async Task ShouldSendACharacterWithSendCharacter()72 {73 await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html");74 await Page.FocusAsync("textarea");75 await Page.Keyboard.SendCharacterAsync("嗨");76 Assert.Equal("嗨", await Page.EvaluateExpressionAsync<string>("document.querySelector('textarea').value"));77 await Page.EvaluateExpressionAsync("window.addEventListener('keydown', e => e.preventDefault(), true)");78 await Page.Keyboard.SendCharacterAsync("a");79 Assert.Equal("嗨a", await Page.EvaluateExpressionAsync<string>("document.querySelector('textarea').value"));80 }81 [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should report shiftKey")]82 [SkipBrowserFact(skipFirefox: true)]83 public async Task ShouldReportShiftKey()84 {85 await Page.GoToAsync(TestConstants.ServerUrl + "/input/keyboard.html");86 var keyboard = Page.Keyboard;87 var codeForKey = new Dictionary<string, int> { ["Shift"] = 16, ["Alt"] = 18, ["Control"] = 17 };88 foreach (var modifier in codeForKey)89 {90 await keyboard.DownAsync(modifier.Key);91 Assert.Equal($"Keydown: {modifier.Key} {modifier.Key}Left {modifier.Value} [{modifier.Key}]", await Page.EvaluateExpressionAsync<string>("getResult()"));92 await keyboard.DownAsync("!");93 // Shift+! will generate a keypress94 if (modifier.Key == "Shift")95 {96 Assert.Equal($"Keydown: ! Digit1 49 [{modifier.Key}]\nKeypress: ! Digit1 33 33 [{modifier.Key}]", await Page.EvaluateExpressionAsync<string>("getResult()"));97 }98 else99 {100 Assert.Equal($"Keydown: ! Digit1 49 [{modifier.Key}]", await Page.EvaluateExpressionAsync<string>("getResult()"));101 }102 await keyboard.UpAsync("!");103 Assert.Equal($"Keyup: ! Digit1 49 [{modifier.Key}]", await Page.EvaluateExpressionAsync<string>("getResult()"));104 await keyboard.UpAsync(modifier.Key);105 Assert.Equal($"Keyup: {modifier.Key} {modifier.Key}Left {modifier.Value} []", await Page.EvaluateExpressionAsync<string>("getResult()"));106 }107 }108 [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should report multiple modifiers")]109 [PuppeteerFact]110 public async Task ShouldReportMultipleModifiers()111 {112 await Page.GoToAsync(TestConstants.ServerUrl + "/input/keyboard.html");113 var keyboard = Page.Keyboard;114 await keyboard.DownAsync("Control");115 Assert.Equal("Keydown: Control ControlLeft 17 [Control]", await Page.EvaluateExpressionAsync<string>("getResult()"));116 await keyboard.DownAsync("Alt");117 Assert.Equal("Keydown: Alt AltLeft 18 [Alt Control]", await Page.EvaluateExpressionAsync<string>("getResult()"));118 await keyboard.DownAsync(";");119 Assert.Equal("Keydown: ; Semicolon 186 [Alt Control]", await Page.EvaluateExpressionAsync<string>("getResult()"));120 await keyboard.UpAsync(";");121 Assert.Equal("Keyup: ; Semicolon 186 [Alt Control]", await Page.EvaluateExpressionAsync<string>("getResult()"));122 await keyboard.UpAsync("Control");123 Assert.Equal("Keyup: Control ControlLeft 17 [Alt]", await Page.EvaluateExpressionAsync<string>("getResult()"));124 await keyboard.UpAsync("Alt");125 Assert.Equal("Keyup: Alt AltLeft 18 []", await Page.EvaluateExpressionAsync<string>("getResult()"));126 }127 [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should send proper codes while typing")]128 [PuppeteerFact]129 public async Task ShouldSendProperCodesWhileTyping()130 {131 await Page.GoToAsync(TestConstants.ServerUrl + "/input/keyboard.html");132 await Page.Keyboard.TypeAsync("!");133 Assert.Equal(string.Join("\n", new[] {134 "Keydown: ! Digit1 49 []",135 "Keypress: ! Digit1 33 33 []",136 "Keyup: ! Digit1 49 []" }), await Page.EvaluateExpressionAsync<string>("getResult()"));137 await Page.Keyboard.TypeAsync("^");138 Assert.Equal(string.Join("\n", new[] {139 "Keydown: ^ Digit6 54 []",140 "Keypress: ^ Digit6 94 94 []",141 "Keyup: ^ Digit6 54 []" }), await Page.EvaluateExpressionAsync<string>("getResult()"));142 }143 [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should send proper codes while typing with shift")]144 [PuppeteerFact]145 public async Task ShouldSendProperCodesWhileTypingWithShift()146 {147 await Page.GoToAsync(TestConstants.ServerUrl + "/input/keyboard.html");148 var keyboard = Page.Keyboard;149 await keyboard.DownAsync("Shift");150 await Page.Keyboard.TypeAsync("~");151 Assert.Equal(string.Join("\n", new[] {152 "Keydown: Shift ShiftLeft 16 [Shift]",153 "Keydown: ~ Backquote 192 [Shift]", // 192 is ` keyCode154 "Keypress: ~ Backquote 126 126 [Shift]", // 126 is ~ charCode155 "Keyup: ~ Backquote 192 [Shift]" }), await Page.EvaluateExpressionAsync<string>("getResult()"));156 await keyboard.UpAsync("Shift");157 }158 [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should not type canceled events")]159 [PuppeteerFact]160 public async Task ShouldNotTypeCanceledEvents()161 {162 await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html");163 await Page.FocusAsync("textarea");164 await Page.EvaluateExpressionAsync(@"{165 window.addEventListener('keydown', event => {166 event.stopPropagation();167 event.stopImmediatePropagation();168 if (event.key === 'l')169 event.preventDefault();170 if (event.key === 'o')171 event.preventDefault();172 }, false);173 }");174 await Page.Keyboard.TypeAsync("Hello World!");175 Assert.Equal("He Wrd!", await Page.EvaluateExpressionAsync<string>("textarea.value"));176 }177 [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should specify repeat property")]178 [SkipBrowserFact(skipFirefox: true)]179 public async Task ShouldSpecifyRepeatProperty()180 {181 await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html");182 await Page.FocusAsync("textarea");183 await Page.EvaluateExpressionAsync("document.querySelector('textarea').addEventListener('keydown', e => window.lastEvent = e, true)");184 await Page.Keyboard.DownAsync("a");185 Assert.False(await Page.EvaluateExpressionAsync<bool>("window.lastEvent.repeat"));186 await Page.Keyboard.PressAsync("a");187 Assert.True(await Page.EvaluateExpressionAsync<bool>("window.lastEvent.repeat"));188 await Page.Keyboard.DownAsync("b");189 Assert.False(await Page.EvaluateExpressionAsync<bool>("window.lastEvent.repeat"));190 await Page.Keyboard.DownAsync("b");191 Assert.True(await Page.EvaluateExpressionAsync<bool>("window.lastEvent.repeat"));192 await Page.Keyboard.UpAsync("a");193 await Page.Keyboard.DownAsync("a");194 Assert.False(await Page.EvaluateExpressionAsync<bool>("window.lastEvent.repeat"));195 }196 [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should type all kinds of characters")]197 [SkipBrowserFact(skipFirefox: true)]198 public async Task ShouldTypeAllKindsOfCharacters()199 {200 await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html");201 await Page.FocusAsync("textarea");202 const string text = "This text goes onto two lines.\nThis character is 嗨.";203 await Page.Keyboard.TypeAsync(text);204 Assert.Equal(text, await Page.EvaluateExpressionAsync<string>("result"));205 }206 [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should specify location")]207 [SkipBrowserFact(skipFirefox: true)]208 public async Task ShouldSpecifyLocation()209 {210 await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html");211 await Page.EvaluateExpressionAsync(@"{212 window.addEventListener('keydown', event => window.keyLocation = event.location, true);213 }");214 var textarea = await Page.QuerySelectorAsync("textarea");215 await textarea.PressAsync("Digit5");...

Full Screen

Full Screen

Form1.cs

Source:Form1.cs Github

copy

Full Screen

...153 //}154 //public async Task FocusElement_ByCssSelector(string selector)155 //{156 // if (usingFrame)157 // await frame.FocusAsync(selector);158 // else159 // await page.FocusAsync(selector);160 //}161 //public async Task TypeText_ByCssSelector(string selector, string val)162 //{163 // if (usingFrame)164 // await frame.TypeAsync(selector, val);165 // else166 // await page.TypeAsync(selector, val);167 //}168 //public async Task Click_ByCssSelector(string selector)169 //{170 // if (usingFrame)171 // await frame.ClickAsync(selector);172 // else173 // await page.ClickAsync(selector);...

Full Screen

Full Screen

Authorization.cs

Source:Authorization.cs Github

copy

Full Screen

...68 Log.Information($"DefaultTimeout: {p.DefaultTimeout}");69 Log.Information($"DefaultNavigationTimeout: {p.DefaultNavigationTimeout}");70 // Авторизация71 await p.WaitForSelectorAsync("#mobileOrEmail", WaitForSelectorTimeout);72 await p.FocusAsync("#mobileOrEmail");73 await p.Keyboard.TypeAsync(ConfigJson.Login);74 Log.Information($"Login: {timer.ElapsedMilliseconds}");75 timer.Restart();76 await p.WaitForSelectorAsync("#password", WaitForSelectorTimeout);77 await p.FocusAsync("#password");78 await p.Keyboard.TypeAsync(ConfigJson.Password);79 Log.Information($"Password: {timer.ElapsedMilliseconds}");80 timer.Restart();81 await p.WaitForSelectorAsync("#loginByPwdButton > span", WaitForSelectorTimeout);82 await p.ClickAsync("#loginByPwdButton > span");83 Log.Information($"ClickAuthorizationButton: {timer.ElapsedMilliseconds}");84 Log.Information("Авторизация: успешно!");85 timer.Stop();86 /* Куки нужны для того, чтобы сайт меня опознал87 * при отправке http-запроса на сервер эл. дневника */88 // 10 попыток получения cookie.89 Cookie cookie;90 int count = 0;91 int attempts = (DefaultTimeout / 1000);...

Full Screen

Full Screen

Program.cs

Source:Program.cs Github

copy

Full Screen

...24 if ((bool)JsonValue.Parse(responseText)["needLogin"])25 {26 await _page.GoToAsync("https://www.epicgames.com/id/login/epic", WaitUntilNavigation.Load);27 await _page.WaitForSelectorAsync("#email");28 await _page.FocusAsync("#email");29 await _page.Keyboard.TypeAsync(Login);30 await _page.FocusAsync("#password");31 await _page.Keyboard.TypeAsync(Password);32 await _page.ClickAsync("#sign-in");33 }34 }35 private static async Task<List<string>> GetAllOrders()36 {37 int page = 0;38 List<OrderHistory.Order> orders = new();39 List<string> items = new();40 OrderHistory.Root orderHistory;41 42 do43 {44 string url = $"https://www.epicgames.com/account/v2/payment/ajaxGetOrderHistory?page={page}&locale=en-US";...

Full Screen

Full Screen

FocusFunction.cs

Source:FocusFunction.cs Github

copy

Full Screen

...35 {36 var element = await page.QuerySelectorByXPath(selector);37 if (element != null)38 {39 await element.FocusAsync();40 }41 else42 {43 throw new Exception($"Node not found with '{selector}' selector on focus function");44 }45 }46 else47 {48 await page.FocusAsync(selector); 49 }50 }51 else52 {53 var currentFrame = page.Frames.FirstOrDefault(x => x.Name == frame);54 if (currentFrame != null)55 {56 if (selector.StartsWith(XPathSelector.XPathSelectorToken))57 {58 var element = await currentFrame.QuerySelectorByXPath(selector);59 if (element != null)60 {61 await element.FocusAsync();62 }63 else64 {65 throw new Exception($"Node not found with '{selector}' selector on focus function");66 }67 }68 else69 {70 await currentFrame.FocusAsync(selector); 71 }72 }73 else74 {75 throw new Exception($"Frame not found with name '{frame}'");76 }77 }78 }79 #endregion80 }81}...

Full Screen

Full Screen

SelectorException.cs

Source:SelectorException.cs Github

copy

Full Screen

...8 /// <seealso cref="Frame.SelectAsync(string, string[])"/>9 /// <seealso cref="Page.ClickAsync(string, Input.ClickOptions)"/>10 /// <seealso cref="Page.TapAsync(string)"/>11 /// <seealso cref="Page.HoverAsync(string)"/>12 /// <seealso cref="Page.FocusAsync(string)"/>13 /// <seealso cref="Page.SelectAsync(string, string[])"/>14 [Serializable]15 public class SelectorException : PuppeteerException16 {17 /// <summary>18 /// Gets the selector.19 /// </summary>20 /// <value>The selector.</value>21 public string Selector { get; }22 /// <summary>23 /// Initializes a new instance of the <see cref="SelectorException"/> class.24 /// </summary>25 /// <param name="message">Message.</param>26 public SelectorException(string message) : base(message)...

Full Screen

Full Screen

FocusAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 {9 };10 using (var browser = await Puppeteer.LaunchAsync(options))11 using (var page = await browser.NewPageAsync())12 {13 await page.FocusAsync("input[title='Search']");

Full Screen

Full Screen

FocusAsync

Using AI Code Generation

copy

Full Screen

1{2 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"3};4using (var browser = await Puppeteer.LaunchAsync(options))5{6 var page = await browser.NewPageAsync();7 await page.FocusAsync("input[title='Search']");8}9{10 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"11};12using (var browser = await Puppeteer.LaunchAsync(options))13{14 var page = await browser.NewPageAsync();15 var element = await page.QuerySelectorAsync("input[title='Search']");16 await element.FocusAsync();17}18{19 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"20};21using (var browser = await Puppeteer.LaunchAsync(options))22{23 var page = await browser.NewPageAsync();24 await page.FocusAsync("input[title='Search']");25}26{27 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"28};29using (var browser = await Puppeteer.LaunchAsync(options))30{31 var page = await browser.NewPageAsync();32 await page.FocusAsync("input[title='Search']");33}34{

Full Screen

Full Screen

FocusAsync

Using AI Code Generation

copy

Full Screen

1var frame = await page.GetMainFrameAsync();2await frame.FocusAsync("input[name='q']");3var element = await page.QuerySelectorAsync("input[name='q']");4await element.FocusAsync();5var element = await page.QuerySelectorAsync("input[name='q']");6await element.FocusAsync();7var element = await page.QuerySelectorAsync("input[name='q']");8await element.FocusAsync();9var element = await page.QuerySelectorAsync("input[name='q']");10await element.FocusAsync();11var element = await page.QuerySelectorAsync("input[name='q']");12await element.FocusAsync();13var element = await page.QuerySelectorAsync("input[name='q']");14await element.FocusAsync();15var element = await page.QuerySelectorAsync("input[name='q']");16await element.FocusAsync();17var element = await page.QuerySelectorAsync("input[name='q']");18await element.FocusAsync();19var element = await page.QuerySelectorAsync("input[name='q']");20await element.FocusAsync();21var element = await page.QuerySelectorAsync("input[name='q']");22await element.FocusAsync();23var element = await page.QuerySelectorAsync("input[name='q']");24await element.FocusAsync();

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful