Best Puppeteer-sharp code snippet using PuppeteerSharp.Input.Touchscreen.Touchscreen
Page.cs
Source:Page.cs
...51 Client = client;52 Target = target;53 Keyboard = new Keyboard(client);54 Mouse = new Mouse(client, Keyboard);55 Touchscreen = new Touchscreen(client, Keyboard);56 Tracing = new Tracing(client);57 Coverage = new Coverage(client);58 _frameManager = new FrameManager(client, frameTree, this);59 _networkManager = new NetworkManager(client, _frameManager);60 _emulationManager = new EmulationManager(client);61 _pageBindings = new Dictionary<string, Delegate>();62 _logger = Client.Connection.LoggerFactory.CreateLogger<Page>();63 _ignoreHTTPSErrors = ignoreHTTPSErrors;64 _screenshotTaskQueue = screenshotTaskQueue;65 _frameManager.FrameAttached += (sender, e) => FrameAttached?.Invoke(this, e);66 _frameManager.FrameDetached += (sender, e) => FrameDetached?.Invoke(this, e);67 _frameManager.FrameNavigated += (sender, e) => FrameNavigated?.Invoke(this, e);68 _networkManager.Request += (sender, e) => Request?.Invoke(this, e);69 _networkManager.RequestFailed += (sender, e) => RequestFailed?.Invoke(this, e);70 _networkManager.Response += (sender, e) => Response?.Invoke(this, e);71 _networkManager.RequestFinished += (sender, e) => RequestFinished?.Invoke(this, e);72 Client.MessageReceived += client_MessageReceived;73 }74 internal CDPSession Client { get; }75 #region Public Properties76 /// <summary>77 /// Raised when the JavaScript <c>load</c> <see href="https://developer.mozilla.org/en-US/docs/Web/Events/load"/> event is dispatched.78 /// </summary>79 public event EventHandler<EventArgs> Load;80 /// <summary>81 /// Raised when the page crashes82 /// </summary>83 public event EventHandler<ErrorEventArgs> Error;84 /// <summary>85 /// Raised when the JavaScript code makes a call to <c>console.timeStamp</c>. For the list of metrics see <see cref="Page.MetricsAsync"/>.86 /// </summary>87 public event EventHandler<MetricEventArgs> Metrics;88 /// <summary>89 /// Raised when a JavaScript dialog appears, such as <c>alert</c>, <c>prompt</c>, <c>confirm</c> or <c>beforeunload</c>. Puppeteer can respond to the dialog via <see cref="Dialog"/>'s <see cref="Dialog.Accept(string)"/> or <see cref="Dialog.Dismiss"/> methods.90 /// </summary>91 public event EventHandler<DialogEventArgs> Dialog;92 /// <summary>93 /// Raised when JavaScript within the page calls one of console API methods, e.g. <c>console.log</c> or <c>console.dir</c>. Also emitted if the page throws an error or a warning.94 /// The arguments passed into <c>console.log</c> appear as arguments on the event handler.95 /// </summary>96 /// <example>97 /// An example of handling <see cref="Console"/> event:98 /// <code>99 /// <![CDATA[100 /// page.Console += (sender, e) => 101 /// {102 /// for (var i = 0; i < e.Message.Args.Count; ++i)103 /// {104 /// System.Console.WriteLine($"{i}: {e.Message.Args[i]}");105 /// }106 /// }107 /// ]]>108 /// </code>109 /// </example>110 public event EventHandler<ConsoleEventArgs> Console;111 /// <summary>112 /// Raised when a frame is attached.113 /// </summary>114 public event EventHandler<FrameEventArgs> FrameAttached;115 /// <summary>116 /// Raised when a frame is detached.117 /// </summary>118 public event EventHandler<FrameEventArgs> FrameDetached;119 /// <summary>120 /// Raised when a frame is navigated to a new url.121 /// </summary>122 public event EventHandler<FrameEventArgs> FrameNavigated;123 /// <summary>124 /// Raised when a <see cref="Response"/> is received.125 /// </summary>126 public event EventHandler<ResponseCreatedEventArgs> Response;127 /// <summary>128 /// Raised when a page issues a request. The <see cref="Request"/> object is read-only.129 /// In order to intercept and mutate requests, see <see cref="SetRequestInterceptionAsync(bool)"/>130 /// </summary>131 public event EventHandler<RequestEventArgs> Request;132 /// <summary>133 /// Raised when a request finishes successfully.134 /// </summary>135 public event EventHandler<RequestEventArgs> RequestFinished;136 /// <summary>137 /// Raised when a request fails, for example by timing out.138 /// </summary>139 public event EventHandler<RequestEventArgs> RequestFailed;140 /// <summary>141 /// Raised when an uncaught exception happens within the page.142 /// </summary>143 public event EventHandler<PageErrorEventArgs> PageError;144 /// <summary>145 /// This setting will change the default maximum navigation time of 30 seconds for the following methods:146 /// - <see cref="GoToAsync(string, NavigationOptions)"/>147 /// - <see cref="GoBackAsync(NavigationOptions)"/>148 /// - <see cref="GoForwardAsync(NavigationOptions)"/>149 /// - <see cref="ReloadAsync(NavigationOptions)"/>150 /// - <see cref="WaitForNavigationAsync(NavigationOptions)"/>151 /// </summary>152 public int DefaultNavigationTimeout { get; set; } = 30000;153 /// <summary>154 /// Gets page's main frame155 /// </summary>156 /// <remarks>157 /// Page is guaranteed to have a main frame which persists during navigations.158 /// </remarks>159 public Frame MainFrame => _frameManager.MainFrame;160 /// <summary>161 /// Gets all frames attached to the page.162 /// </summary>163 /// <value>An array of all frames attached to the page.</value>164 public Frame[] Frames => _frameManager.Frames.Values.ToArray();165 /// <summary>166 /// Shortcut for <c>page.MainFrame.Url</c>167 /// </summary>168 public string Url => MainFrame.Url;169 /// <summary>170 /// Gets that target this page was created from.171 /// </summary>172 public Target Target { get; }173 /// <summary>174 /// Gets this page's keyboard175 /// </summary>176 public Keyboard Keyboard { get; }177 /// <summary>178 /// Gets this page's touchscreen179 /// </summary>180 public Touchscreen Touchscreen { get; }181 /// <summary>182 /// Gets this page's coverage183 /// </summary>184 public Coverage Coverage { get; }185 /// <summary>186 /// Gets this page's tracing187 /// </summary>188 public Tracing Tracing { get; }189 /// <summary>190 /// Gets this page's mouse191 /// </summary>192 public Mouse Mouse { get; }193 /// <summary>194 /// Gets this page's viewport195 /// </summary>196 public ViewPortOptions Viewport { get; private set; }197 /// <summary>198 /// List of suported metrics provided by the <see cref="Metrics"/> event.199 /// </summary>200 public static readonly IEnumerable<string> SupportedMetrics = new List<string>201 {202 "Timestamp",203 "Documents",204 "Frames",205 "JSEventListeners",206 "Nodes",207 "LayoutCount",208 "RecalcStyleCount",209 "LayoutDuration",210 "RecalcStyleDuration",211 "ScriptDuration",212 "TaskDuration",213 "JSHeapUsedSize",214 "JSHeapTotalSize"215 };216 #endregion217 #region Public Methods218 /// <summary>219 /// Returns metrics220 /// </summary>221 /// <returns>Task which resolves into a list of metrics</returns>222 /// <remarks>223 /// All timestamps are in monotonic time: monotonically increasing time in seconds since an arbitrary point in the past.224 /// </remarks>225 public async Task<Dictionary<string, decimal>> MetricsAsync()226 {227 var response = await Client.SendAsync<PerformanceGetMetricsResponse>("Performance.getMetrics");228 return BuildMetricsObject(response.Metrics);229 }230 /// <summary>231 /// Fetches an element with <paramref name="selector"/>, scrolls it into view if needed, and then uses <see cref="Touchscreen"/> to tap in the center of the element.232 /// </summary>233 /// <param name="selector">A selector to search for element to tap. If there are multiple elements satisfying the selector, the first will be clicked.</param>234 /// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>235 /// <returns>Task which resolves when the element matching <paramref name="selector"/> is successfully tapped</returns>236 public async Task TapAsync(string selector)237 {238 var handle = await QuerySelectorAsync(selector);239 if (handle == null)240 {241 throw new SelectorException($"No node found for selector: {selector}", selector);242 }243 await handle.TapAsync();244 await handle.DisposeAsync();245 }...
ElementHandle.cs
Source:ElementHandle.cs
...177 var objectId = RemoteObject[MessageKeys.ObjectId].AsString();178 return Client.SendAsync("DOM.setFileInputFiles", new { objectId, files });179 }180 /// <summary>181 /// Scrolls element into view if needed, and then uses <see cref="Touchscreen.TapAsync(decimal, decimal)"/> to tap in the center of the element.182 /// </summary>183 /// <exception cref="PuppeteerException">if the element is detached from DOM</exception>184 /// <returns>Task which resolves when the element is successfully tapped</returns>185 public async Task TapAsync()186 {187 await ScrollIntoViewIfNeededAsync().ConfigureAwait(false);188 var (x, y) = await ClickablePointAsync().ConfigureAwait(false);189 await Page.Touchscreen.TapAsync(x, y).ConfigureAwait(false);190 }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>...
Index.cshtml.cs
Source:Index.cshtml.cs
...77 var left = rect.X + 10;78 var top = rect.Y + 10;79 var mouse = page.Mouse;80 await mouse.MoveAsync(left, top);81 await page.Touchscreen.TapAsync(left, top);82 await mouse.DownAsync();83 var startTime = DateTime.Now;84 await mouse.MoveAsync(left + 800, top, new PuppeteerSharp.Input.MoveOptions { Steps = 30 });85 await page.Touchscreen.TapAsync(left + 800, top);86 Console.WriteLine(DateTime.Now - startTime);87 await mouse.UpAsync();88 var success = await page.WaitForSelectorAsync(".yes", new WaitForSelectorOptions { Timeout = 3000 });89 string content = await page.GetContentAsync();90 91 var parser = new HtmlParser();92 var document = await parser.ParseDocumentAsync(content);93 aliToken = (document.GetElementById("aliToken") as IHtmlInputElement).GetAttribute("sms");94 aliSessionId = (document.GetElementById("aliSessionId") as IHtmlInputElement).GetAttribute("sms");95 aliSig = (document.GetElementById("aliSig") as IHtmlInputElement).GetAttribute("sms");96 }97 var response = await "https://upay.10010.com/npfwap/NpfMob/needdubbo/needDubboCheck?phoneNo=13113075869&amountMoney=200&channelKey=wxgz"98 .WithHeaders(new { Referer = "https://upay.10010.com/jf_wxgz" })99 .WithCookies(cookies)...
pay.cshtml.cs
Source:pay.cshtml.cs
...53 var left = rect.X + 10;54 var top = rect.Y + 10;55 var mouse = page.Mouse;56 await mouse.MoveAsync(left, top);57 await page.Touchscreen.TapAsync(left, top);58 await mouse.DownAsync();59 var startTime = DateTime.Now;60 await mouse.MoveAsync(left + 800, top, new PuppeteerSharp.Input.MoveOptions { Steps = 30 });61 await page.Touchscreen.TapAsync(left + 800, top);62 Console.WriteLine(DateTime.Now - startTime);63 await mouse.UpAsync();64 }65 var channel = await page.WaitForSelectorAsync("[channelcode='alipaywap']");66 await channel.ClickAsync();67 var submit = await page.WaitForSelectorAsync("body > div.mask.confirmPay > section > div.btnPd > button");68 await submit.ClickAsync();69 }70 }71}...
Touchscreen.cs
Source:Touchscreen.cs
...5{6 /// <summary>7 /// Provides methods to interact with the touch screen8 /// </summary>9 public class Touchscreen10 {11 private readonly CDPSession _client;12 private readonly Keyboard _keyboard;13 /// <summary>14 /// Initializes a new instance of the <see cref="Touchscreen"/> class.15 /// </summary>16 /// <param name="client">The client</param>17 /// <param name="keyboard">The keyboard</param>18 public Touchscreen(CDPSession client, Keyboard keyboard)19 {20 _client = client;21 _keyboard = keyboard;22 }23 /// <summary>24 /// Dispatches a <c>touchstart</c> and <c>touchend</c> event.25 /// </summary>26 /// <param name="x"></param>27 /// <param name="y"></param>28 /// <returns>Task</returns>29 /// <seealso cref="Page.TapAsync(string)"/>30 public async Task TapAsync(decimal x, decimal y)31 {32 // Touches appear to be lost during the first frame after navigation....
TouchScreenTests.cs
Source:TouchScreenTests.cs
...12 private readonly DeviceDescriptor _iPhone = Puppeteer.Devices[DeviceDescriptorName.IPhone6];13 public TouchScreenTests(ITestOutputHelper output) : base(output)14 {15 }16 [PuppeteerTest("touchscreen.spec.ts", "Touchscreen", "should tap the button")]17 [SkipBrowserFact(skipFirefox: true)]18 public async Task ShouldTapTheButton()19 {20 await Page.EmulateAsync(_iPhone);21 await Page.GoToAsync(TestConstants.ServerUrl + "/input/button.html");22 await Page.TapAsync("button");23 Assert.Equal("Clicked", await Page.EvaluateExpressionAsync<string>("result"));24 }25 [PuppeteerTest("touchscreen.spec.ts", "Touchscreen", "should report touches")]26 [SkipBrowserFact(skipFirefox: true)]27 public async Task ShouldReportTouches()28 {29 await Page.EmulateAsync(_iPhone);30 await Page.GoToAsync(TestConstants.ServerUrl + "/input/touches.html");31 var button = await Page.QuerySelectorAsync("button");32 await button.TapAsync();33 Assert.Equal(new string[] {34 "Touchstart: 0",35 "Touchend: 0"36 }, await Page.EvaluateExpressionAsync<string[]>("getResult()"));37 }38 }39}...
Touchscreen
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 await page.WaitForSelectorAsync("input[name='q']");14 var input = await page.QuerySelectorAsync("input[name='q']");15 await input.ClickAsync();16 await page.Touchscreen.TapAsync(200, 200);17 await page.Touchscreen.TapAsync(300, 300);18 await page.Touchscreen.TapAsync(400, 400);19 await page.Touchscreen.TapAsync(500, 500);20 await page.Touchscreen.TapAsync(600, 600);21 await page.Touchscreen.TapAsync(700, 700);22 await page.Touchscreen.TapAsync(800, 800);23 await page.Touchscreen.TapAsync(900, 900);24 await page.Touchscreen.TapAsync(1000, 1000);25 await page.Touchscreen.TapAsync(1100, 1100);26 await page.Touchscreen.TapAsync(1200, 1200);27 await page.Touchscreen.TapAsync(1300, 1300);28 await page.Touchscreen.TapAsync(1400, 1400);29 await page.Touchscreen.TapAsync(1500, 1500);30 await page.Touchscreen.TapAsync(1600, 1600);31 await page.Touchscreen.TapAsync(1700, 1700);32 await page.Touchscreen.TapAsync(1800, 1800);33 await page.Touchscreen.TapAsync(1900, 1900);34 await page.Touchscreen.TapAsync(2000, 2000);35 await page.WaitForTimeoutAsync(3000);36 await browser.CloseAsync();37 }38 }39}40using System;41using System.Threading.Tasks;42using PuppeteerSharp;43{44 {45 static async Task Main(string[] args)
Touchscreen
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 static async Task Main(string[] args)6 {7 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);8 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))9 using (var page = await browser.NewPageAsync())10 {11 await page.SetViewportAsync(new ViewPortOptions { Width = 1920, Height = 1080 });12 await page.Touchscreen.TapAsync(100, 100);13 await page.ScreenshotAsync("1.png");14 }15 }16}17using PuppeteerSharp;18using System;19using System.Threading.Tasks;20{21 static async Task Main(string[] args)22 {23 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);24 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))25 using (var page = await browser.NewPageAsync())26 {27 await page.SetViewportAsync(new ViewPortOptions { Width = 1920, Height = 1080 });28 await PuppeteerSharp.Input.Touchscreen.TapAsync(page, 100, 100);29 await page.ScreenshotAsync("2.png");30 }31 }32}33 at PuppeteerSharp.Input.Touchscreen.TapAsync(Page page, Double x, Double y, Int32 timeout) in C:\projects\puppeteer-sharp\lib\PuppeteerSharp\Input\Touchscreen.cs:line 6434 at PuppeteerSharp.Input.Touchscreen.TapAsync(Page page, Double x, Double y) in C:\projects\puppeteer-sharp\lib\PuppeteerSharp\Input\Touchscreen.cs:line 5435 at PuppeteerSharp.Input.Touchscreen.TapAsync(Page page, Double x, Double y) in C:\projects\puppeteer-sharp\lib\PuppeteerSharp\Input\Touchscreen.cs:line 5636 at PuppeteerSharp.Input.Touchscreen.TapAsync(Page page
Touchscreen
Using AI Code Generation
1using System.Threading.Tasks;2using PuppeteerSharp;3{4 {5 static async Task Main(string[] args)6 {7 var options = new LaunchOptions { Headless = false };8 using (var browser = await Puppeteer.LaunchAsync(options))9 using (var page = await browser.NewPageAsync())10 {11 await page.WaitForSelectorAsync("input[name=q]");12 await page.FocusAsync("input[name=q]");13 await page.Keyboard.TypeAsync("puppeteer-sharp");14 await page.Touchscreen.TapAsync(500, 500);15 }16 }17 }18}
Touchscreen
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4using PuppeteerSharp.Input;5using System.Collections.Generic;6{7 {8 static async Task Main(string[] args)9 {10 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);11 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });12 var page = await browser.NewPageAsync();13 var viewport = page.Viewport;14 var size = await page.EvaluateExpressionAsync<Dictionary<string, int>>("document.body.getBoundingClientRect()");15 await page.SetViewportAsync(new ViewPortOptions16 {17 });18 var touchScreen = new Touchscreen(page);19 {20 };21 await touchScreen.TapAsync(touchPoint.X, touchPoint.Y);22 await Task.Delay(5000);23 await browser.CloseAsync();24 }25 }26}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!